-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbooru-exception.interceptor.ts
More file actions
320 lines (261 loc) · 9.88 KB
/
Copy pathbooru-exception.interceptor.ts
File metadata and controls
320 lines (261 loc) · 9.88 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import {
CallHandler,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
MethodNotAllowedException,
NestInterceptor,
ServiceUnavailableException,
UnauthorizedException
} from '@nestjs/common'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'
import { EmptyDataError, EndpointError, HttpError } from '@alejandroakbal/universal-booru-wrapper'
import { NoContentException } from '../../common/exceptions/no-content.exception'
import { BooruAuthManagerService } from '../services/booru-auth-manager.service'
import { AuthFailureEvent } from '../interfaces/auth-manager.interface'
import { BOORU_CACHE_CONTROL_POLICIES } from '../constants/cache-control-policies'
import { SENSITIVE_AUTH_PARAMS } from '../constants/sensitive-auth-params'
import { ManagedCredentialPoolUnavailableError } from '../booru.service'
import type { BooruHttpRequest } from '../interfaces/booru-http.interface'
interface HeaderResponse {
header(name: string, value: string): void
}
function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message || error.toString()
}
return String(error)
}
@Injectable()
export class BooruErrorsInterceptor implements NestInterceptor {
constructor(private readonly authManager: BooruAuthManagerService) {}
// Common booru authentication parameters that should be redacted from error messages
private readonly sensitiveParams = SENSITIVE_AUTH_PARAMS
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
return next.handle().pipe(
catchError((error: unknown) => {
const response = context.switchToHttp().getResponse<HeaderResponse | undefined>()
if (response && typeof response.header === 'function') {
response.header('Cache-Control', BOORU_CACHE_CONTROL_POLICIES.ERROR)
}
// Check for authentication failures before processing other errors
this.checkForAuthFailure(error, context)
// Sanitize error messages to remove authentication data
const sanitizedMessage = this.sanitizeErrorMessage(getErrorMessage(error))
if (error instanceof ManagedCredentialPoolUnavailableError) {
const retryAfterSeconds = this.getRetryAfterSeconds(error)
if (retryAfterSeconds !== undefined) {
response?.header('Retry-After', `${retryAfterSeconds}`)
}
return throwError(
() =>
new HttpException(
{
statusCode: HttpStatus.SERVICE_UNAVAILABLE,
message: sanitizedMessage,
retryAfterSeconds,
reason: error.reason
},
HttpStatus.SERVICE_UNAVAILABLE
)
)
}
if (error instanceof EmptyDataError) {
return throwError(() => new NoContentException(undefined, sanitizedMessage))
}
if (error instanceof EndpointError) {
return throwError(() => new MethodNotAllowedException(undefined, sanitizedMessage))
}
if (error instanceof HttpError) {
// Check if this is an auth-related HTTP error
if (this.isCredentialFailure(error)) {
return throwError(() => new UnauthorizedException(undefined, sanitizedMessage))
}
if (this.isRateLimitError(error)) {
const retryAfterSeconds = this.getRetryAfterSeconds(error)
if (retryAfterSeconds !== undefined) {
response?.header('Retry-After', `${retryAfterSeconds}`)
}
return throwError(
() =>
new HttpException(
{
statusCode: HttpStatus.BAD_GATEWAY,
error: 'Bad Gateway',
message: sanitizedMessage,
upstreamStatusCode: HttpStatus.TOO_MANY_REQUESTS,
retryAfterSeconds
},
HttpStatus.BAD_GATEWAY
)
)
}
return throwError(() => new ServiceUnavailableException(undefined, sanitizedMessage))
}
// For unknown errors, also sanitize the message
const sanitizedError = new Error(sanitizedMessage)
if (error instanceof Error) {
sanitizedError.name = error.name
if (error.stack !== undefined && error.stack !== '') {
sanitizedError.stack = this.sanitizeErrorMessage(error.stack)
}
}
return throwError(() => sanitizedError)
})
)
}
/**
* Sanitizes error messages by removing sensitive authentication parameters from URLs
*/
private sanitizeErrorMessage(message: string): string {
if (!message) {
return message
}
const urlPattern = /https?:\/\/[^\s]+/gi
return message.replace(urlPattern, (url) => this.sanitizeUrl(url))
}
/**
* Sanitizes a single URL by removing sensitive query parameters using native URL API
*/
private sanitizeUrl(url: string): string {
try {
const urlObj = new URL(url)
// Check each query parameter and redact sensitive ones
for (const [key] of urlObj.searchParams.entries()) {
if (this.sensitiveParams.some((param) => param.toLowerCase() === key.toLowerCase())) {
urlObj.searchParams.set(key, 'REDACTED')
}
}
return urlObj.toString()
} catch {
return this.sanitizeRawUrl(url)
}
}
private sanitizeRawUrl(url: string): string {
let sanitizedUrl = url
for (const key of this.sensitiveParams) {
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const pattern = new RegExp(`([?&]${escapedKey}=)[^&#\\s]*`, 'gi')
sanitizedUrl = sanitizedUrl.replace(pattern, '$1REDACTED')
}
return sanitizedUrl
}
private checkForAuthFailure(error: unknown, context: ExecutionContext): void {
if (!this.isCredentialFailure(error) && !this.isRateLimitError(error)) {
return
}
const request = context.switchToHttp().getRequest<BooruHttpRequest>()
if (request.booruAuthContext?.source) {
return
}
const contextCredential = request.booruAuthContext?.credential
const baseEndpoint =
request.booruAuthContext?.baseEndpoint ?? request.query?.baseEndpoint ?? request.body?.baseEndpoint
const authUser = contextCredential?.user ?? request.query?.auth_user ?? request.body?.auth_user
const authPass = contextCredential?.password ?? request.query?.auth_pass ?? request.body?.auth_pass
if (baseEndpoint === undefined || baseEndpoint === '' || authUser === undefined || authUser === '') {
return
}
const domain = this.extractDomainFromUrl(baseEndpoint)
const authFailure: AuthFailureEvent = {
domain,
user: authUser,
error: this.getAuthErrorMessage(error),
timestamp: new Date()
}
if (authPass !== undefined) {
authFailure.password = authPass
}
const failureKind = this.getFailureKind(error)
if (failureKind !== undefined) {
authFailure.failureKind = failureKind
}
const retryAfterSeconds = this.getRetryAfterSeconds(error)
if (retryAfterSeconds !== undefined) {
authFailure.retryAfterSeconds = retryAfterSeconds
}
this.authManager.reportAuthFailure(authFailure)
}
private isCredentialFailure(error: unknown): boolean {
if (error instanceof HttpError) {
const failureKind = error.failureKind
const statusCode = error.statusCode
if (failureKind === 'auth_invalid' || failureKind === 'auth_forbidden') {
return true
}
if (statusCode === 401 || statusCode === 403) {
return true
}
}
const errorMessage = getErrorMessage(error).toLowerCase()
const authErrorPatterns = [
'unauthorized',
'forbidden',
'authentication failed',
'invalid credentials',
'access denied',
'login required',
'invalid api key',
'invalid user',
'authentication required'
]
return authErrorPatterns.some((pattern) => errorMessage.includes(pattern))
}
private isRateLimitError(error: unknown): boolean {
if (error instanceof HttpError) {
const failureKind = error.failureKind
const statusCode = error.statusCode
if (failureKind === 'rate_limited') {
return true
}
if (statusCode === 429) {
return true
}
}
const errorMessage = getErrorMessage(error).toLowerCase()
return errorMessage.includes('status: 429') || errorMessage.includes('http 429')
}
private getAuthErrorMessage(error: unknown): string {
if (error instanceof HttpError) {
return `HTTP ${error.statusCode ?? 'unknown'}: ${error.message || 'Authentication error'}`
}
return getErrorMessage(error) || 'Unknown authentication error'
}
private getFailureKind(error: unknown): AuthFailureEvent['failureKind'] {
if (error instanceof HttpError) {
return error.failureKind
}
if (this.isRateLimitError(error)) {
return 'rate_limited'
}
if (this.isCredentialFailure(error)) {
return 'auth_forbidden'
}
return 'unknown'
}
private getRetryAfterSeconds(error: unknown): number | undefined {
if (
(error instanceof HttpError || error instanceof ManagedCredentialPoolUnavailableError) &&
typeof error.retryAfterSeconds === 'number' &&
Number.isFinite(error.retryAfterSeconds) &&
error.retryAfterSeconds >= 0
) {
return Math.floor(error.retryAfterSeconds)
}
return undefined
}
private extractDomainFromUrl(url: string): string {
try {
const hasProtocol = /^https?:\/\//i.test(url)
const normalizedUrl = hasProtocol ? url : `https://${url}`
const urlObj = new URL(normalizedUrl)
return urlObj.hostname.toLowerCase()
} catch {
const [urlWithoutQuery = ''] = url.replace(/^(https?:\/\/)?/i, '').split(/[?#]/)
const [domain = ''] = urlWithoutQuery.split('/')
return domain.toLowerCase()
}
}
}