-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbooru.service.spec.ts
More file actions
728 lines (607 loc) · 24.3 KB
/
Copy pathbooru.service.spec.ts
File metadata and controls
728 lines (607 loc) · 24.3 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
import type { TestingModule } from '@nestjs/testing'
import { Test } from '@nestjs/testing'
import { ConfigService } from '@nestjs/config'
import { BooruTypesStringEnum, HttpError } from '@alejandroakbal/universal-booru-wrapper'
import type { ManagedCredentialPoolUnavailableError } from './booru.service'
import { BooruService } from './booru.service'
import type { booruQueriesDTO } from './dto/booru-queries.dto'
import type { BooruEndpointParamsDTO } from './dto/request-booru.dto'
import { BooruAuthManagerService } from './services/booru-auth-manager.service'
interface MockAuthManager {
reserveAvailableCredential: jest.MockedFunction<BooruAuthManagerService['reserveAvailableCredential']>
getDomainStats: jest.MockedFunction<BooruAuthManagerService['getDomainStats']>
reportAuthFailure: jest.MockedFunction<BooruAuthManagerService['reportAuthFailure']>
getMinCooldownSeconds: jest.MockedFunction<BooruAuthManagerService['getMinCooldownSeconds']>
}
interface ApiAuth {
username?: string
apiKey?: string
}
interface ApiAuthOptions {
options?: {
auth?: ApiAuth
}
}
function getApiAuth(api: unknown): ApiAuth | undefined {
return (api as ApiAuthOptions).options?.auth
}
function buildPostUrl(api: unknown): URL {
const internalApi = api as {
generateEndpointUrl(endpoint: string): URL
addPostQueries(url: URL, queries: { limit: number; pageID: number; tags: string[] }): URL
}
return internalApi.addPostQueries(internalApi.generateEndpointUrl('/index.php?page=dapi&s=post&q=index'), {
limit: 1,
pageID: 1,
tags: ['diana']
})
}
function buildTagUrl(api: unknown): URL {
const internalApi = api as {
generateEndpointUrl(endpoint: string): URL
addTagsQueries(url: URL, queries: { tag: string; limit: number }): URL
}
return internalApi.addTagsQueries(internalApi.generateEndpointUrl('/index.php?page=dapi&s=tag&q=index'), {
tag: 'dian',
limit: 1
})
}
describe('BooruService', () => {
let service: BooruService
let mockAuthManager: MockAuthManager
const mockConfigService = {
get: jest.fn()
}
const mockParams: BooruEndpointParamsDTO = {
booruType: BooruTypesStringEnum.GELBOORU_COM
}
const baseQueries: Partial<booruQueriesDTO> = {
baseEndpoint: 'https://gelbooru.com'
}
beforeEach(async () => {
mockConfigService.get.mockReset()
mockAuthManager = {
reserveAvailableCredential: jest.fn() as jest.MockedFunction<
BooruAuthManagerService['reserveAvailableCredential']
>,
getDomainStats: jest.fn() as jest.MockedFunction<BooruAuthManagerService['getDomainStats']>,
reportAuthFailure: jest.fn() as jest.MockedFunction<BooruAuthManagerService['reportAuthFailure']>,
getMinCooldownSeconds: jest.fn() as jest.MockedFunction<BooruAuthManagerService['getMinCooldownSeconds']>
}
const module: TestingModule = await Test.createTestingModule({
providers: [
BooruService,
{
provide: ConfigService,
useValue: mockConfigService
},
{
provide: BooruAuthManagerService,
useValue: mockAuthManager
}
]
}).compile()
service = module.get<BooruService>(BooruService)
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'gelbooru.com',
total: 1,
available: 1,
disabled: 0,
cooldown: 0,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential.mockResolvedValue({ user: 'managed_1', password: 'pass_1' })
})
describe('Authentication Resolution', () => {
it('should use query parameters when both auth_user and auth_pass are provided', () => {
const queries = {
...baseQueries,
auth_user: 'query_user',
auth_pass: 'query_pass'
} as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
expect(getApiAuth(api)?.username).toBe('query_user')
expect(getApiAuth(api)?.apiKey).toBe('query_pass')
})
it('should not use managed credentials while building metadata APIs', () => {
// Test with no query params
const queriesNoAuth = { ...baseQueries } as booruQueriesDTO
const apiNoAuth = service.buildApiClass(mockParams, queriesNoAuth)
expect(getApiAuth(apiNoAuth)?.username).toBeUndefined()
expect(getApiAuth(apiNoAuth)?.apiKey).toBeUndefined()
// Test with partial query params (should still use env)
const queriesPartial = {
...baseQueries,
auth_user: 'partial_user' // Missing auth_pass
} as booruQueriesDTO
const apiPartial = service.buildApiClass(mockParams, queriesPartial)
expect(getApiAuth(apiPartial)?.username).toBeUndefined()
expect(getApiAuth(apiPartial)?.apiKey).toBeUndefined()
})
it('should use query parameters when building metadata APIs', () => {
const queries = {
...baseQueries,
auth_user: 'query_user',
auth_pass: 'query_pass'
} as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
expect(getApiAuth(api)?.username).toBe('query_user')
expect(getApiAuth(api)?.apiKey).toBe('query_pass')
})
it('should create metadata API without authentication when no query credentials are available', () => {
const queries = { ...baseQueries } as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
expect(getApiAuth(api)?.username).toBeUndefined()
expect(getApiAuth(api)?.apiKey).toBeUndefined()
})
it('should expose selected credential metadata when building API with an auth override', () => {
const queries = { ...baseQueries } as booruQueriesDTO
const result = service.buildApiWithContext(mockParams, queries, {
auth: { username: 'managed_user', apiKey: 'managed_pass' },
source: 'env',
selectedCredential: { user: 'managed_user', password: 'managed_pass' }
})
expect(getApiAuth(result.api)?.username).toBe('managed_user')
expect(result.authResolution.source).toBe('env')
expect(result.authResolution.selectedCredential).toEqual({
user: 'managed_user',
password: 'managed_pass'
})
})
it('should not use managed credentials when building API context without an override', () => {
const queries = { ...baseQueries } as booruQueriesDTO
const result = service.buildApiWithContext(mockParams, queries)
expect(result.authResolution.source).toBe('none')
expect(getApiAuth(result.api)?.username).toBeUndefined()
expect(getApiAuth(result.api)?.apiKey).toBeUndefined()
})
it('should expose query credential metadata when query auth is provided', () => {
const queries = {
...baseQueries,
auth_user: 'query_user',
auth_pass: 'query_pass'
} as booruQueriesDTO
const result = service.buildApiWithContext(mockParams, queries)
expect(result.authResolution.source).toBe('query')
expect(result.authResolution.selectedCredential).toEqual({
user: 'query_user',
password: 'query_pass'
})
})
})
describe('Outbound Proxy Resolution', () => {
it('should proxy configured provider URLs after query and auth parameters are applied', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': {
baseUrl: 'https://cors-proxy2.rule34.workers.dev/',
targetParam: 'q'
}
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com',
auth_user: 'managed_1',
auth_pass: 'pass_1'
} as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
const proxiedUrl = buildPostUrl(api)
const upstreamUrl = new URL(proxiedUrl.searchParams.get('q') ?? '')
expect(proxiedUrl.origin).toBe('https://cors-proxy2.rule34.workers.dev')
expect(upstreamUrl.origin).toBe('https://gelbooru.com')
expect(upstreamUrl.searchParams.get('limit')).toBe('1')
expect(upstreamUrl.searchParams.get('pid')).toBe('1')
expect(upstreamUrl.searchParams.get('tags')).toBe('diana')
expect(upstreamUrl.searchParams.get('user_id')).toBe('managed_1')
expect(upstreamUrl.searchParams.get('api_key')).toBe('pass_1')
expect(proxiedUrl.searchParams.has('userAgent')).toBe(false)
})
it('should bypass Cloudflare proxy policies for e621', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'e621.net': {
baseUrl: 'https://cors-proxy2.rule34.workers.dev/',
targetParam: 'q'
}
})
}
return undefined
})
const api = service.buildApiClass(mockParams, { ...baseQueries, baseEndpoint: 'e621.net' } as booruQueriesDTO)
const outboundUrl = buildPostUrl(api)
expect(outboundUrl.origin).toBe('https://e621.net')
})
it('should attach forward proxy options when BOORU_FORWARD_PROXY_CONFIG is set', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_FORWARD_PROXY_CONFIG') {
return JSON.stringify({
'e621.net': 'http://smart-proxy.akbal.dev:24000/'
})
}
return undefined
})
const api = service.buildApiClass(mockParams, { ...baseQueries, baseEndpoint: 'e621.net' } as booruQueriesDTO)
expect((api as unknown as { options: { proxy?: string } }).options.proxy).toBe(
'http://smart-proxy.akbal.dev:24000/'
)
})
it('should throw when BOORU_FORWARD_PROXY_CONFIG is not valid JSON', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_FORWARD_PROXY_CONFIG') {
return '{ invalid json'
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'e621.net'
} as booruQueriesDTO
expect(() => service.buildApiClass(mockParams, queries)).toThrow('Failed to parse BOORU_FORWARD_PROXY_CONFIG')
})
it('should throw when BOORU_FORWARD_PROXY_CONFIG contains an invalid proxy URL', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_FORWARD_PROXY_CONFIG') {
return JSON.stringify({
'e621.net': 'not-a-valid-url'
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'e621.net'
} as booruQueriesDTO
expect(() => service.buildApiClass(mockParams, queries)).toThrow(
'Invalid BOORU_FORWARD_PROXY_CONFIG proxy URL for e621.net'
)
})
it('should throw when BOORU_FORWARD_PROXY_CONFIG is not an object', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_FORWARD_PROXY_CONFIG') {
return JSON.stringify(['http://smart-proxy.akbal.dev:24000/'])
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'e621.net'
} as booruQueriesDTO
expect(() => service.buildApiClass(mockParams, queries)).toThrow('Invalid BOORU_FORWARD_PROXY_CONFIG')
})
it('should proxy configured provider tag URLs with the same policy', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': {
baseUrl: 'https://r34.app/api/cors-proxy/',
targetParam: 'q'
}
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com',
auth_user: 'managed_1',
auth_pass: 'pass_1'
} as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
const proxiedUrl = buildTagUrl(api)
const upstreamUrl = new URL(proxiedUrl.searchParams.get('q') ?? '')
expect(proxiedUrl.origin).toBe('https://r34.app')
expect(proxiedUrl.pathname).toBe('/api/cors-proxy/')
expect(upstreamUrl.origin).toBe('https://gelbooru.com')
expect(upstreamUrl.searchParams.get('name_pattern')).toBe('dian%')
expect(upstreamUrl.searchParams.get('limit')).toBe('1')
expect(upstreamUrl.searchParams.get('user_id')).toBe('managed_1')
expect(upstreamUrl.searchParams.get('api_key')).toBe('pass_1')
})
it('should leave unconfigured provider URLs direct', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'rule34.xxx': {
baseUrl: 'https://cors-proxy2.rule34.workers.dev/',
targetParam: 'q'
}
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com',
auth_user: 'managed_1',
auth_pass: 'pass_1'
} as booruQueriesDTO
const api = service.buildApiClass(mockParams, queries)
const directUrl = buildPostUrl(api)
expect(directUrl.origin).toBe('https://gelbooru.com')
expect(directUrl.searchParams.get('q')).toBe('index')
expect(directUrl.searchParams.get('user_id')).toBe('managed_1')
expect(directUrl.searchParams.get('api_key')).toBe('pass_1')
})
it('should rotate through multiple configured provider proxies', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': [
{
baseUrl: 'https://cors-proxy2.rule34.workers.dev/',
targetParam: 'q'
},
{
baseUrl: 'https://cors-proxy.refinedsoftware00.workers.dev/',
targetParam: 'q'
}
]
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com',
auth_user: 'managed_1',
auth_pass: 'pass_1'
} as booruQueriesDTO
const firstUrl = buildPostUrl(service.buildApiClass(mockParams, queries))
const secondUrl = buildPostUrl(service.buildApiClass(mockParams, queries))
const thirdUrl = buildPostUrl(service.buildApiClass(mockParams, queries))
expect(firstUrl.origin).toBe('https://cors-proxy2.rule34.workers.dev')
expect(secondUrl.origin).toBe('https://cors-proxy.refinedsoftware00.workers.dev')
expect(thirdUrl.origin).toBe('https://cors-proxy2.rule34.workers.dev')
})
it('should not rotate proxies while building an API that never fetches', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': [
{
baseUrl: 'https://cors-proxy2.rule34.workers.dev/',
targetParam: 'q'
},
{
baseUrl: 'https://cors-proxy.refinedsoftware00.workers.dev/',
targetParam: 'q'
}
]
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com',
auth_user: 'managed_1',
auth_pass: 'pass_1'
} as booruQueriesDTO
service.buildApiClass(mockParams, queries)
const firstFetchedUrl = buildPostUrl(service.buildApiClass(mockParams, queries))
const secondFetchedUrl = buildPostUrl(service.buildApiClass(mockParams, queries))
expect(firstFetchedUrl.origin).toBe('https://cors-proxy2.rule34.workers.dev')
expect(secondFetchedUrl.origin).toBe('https://cors-proxy.refinedsoftware00.workers.dev')
})
it('should reject invalid outbound proxy config shapes', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': {
baseUrl: 'not-a-url',
targetParam: 'q'
}
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com'
} as booruQueriesDTO
expect(() => service.buildApiClass(mockParams, queries)).toThrow(
'Invalid BOORU_OUTBOUND_PROXY_CONFIG baseUrl for gelbooru.com'
)
})
it('should reject plaintext outbound proxy URLs', () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_OUTBOUND_PROXY_CONFIG') {
return JSON.stringify({
'gelbooru.com': {
baseUrl: 'http://cors-proxy.example.test/',
targetParam: 'q'
}
})
}
return undefined
})
const queries = {
...baseQueries,
baseEndpoint: 'gelbooru.com'
} as booruQueriesDTO
expect(() => service.buildApiClass(mockParams, queries)).toThrow(
'Invalid BOORU_OUTBOUND_PROXY_CONFIG baseUrl for gelbooru.com'
)
})
})
describe('Managed Strategy Execution', () => {
it('should not fallback when explicit auth is provided', async () => {
const queries = {
...baseQueries,
auth_user: 'explicit_user',
auth_pass: 'explicit_pass'
} as booruQueriesDTO
const operation = jest.fn().mockResolvedValue('ok')
const result = await service.executeWithAuthStrategy(mockParams, queries, operation)
expect(result).toBe('ok')
expect(mockAuthManager.reportAuthFailure).not.toHaveBeenCalled()
})
it('should retry with another managed credential after rate limit failure', async () => {
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'gelbooru.com',
total: 2,
available: 2,
disabled: 0,
cooldown: 0,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential
.mockResolvedValueOnce({ user: 'managed_1', password: 'pass_1' })
.mockResolvedValueOnce({ user: 'managed_2', password: 'pass_2' })
const queries = { ...baseQueries } as booruQueriesDTO
const operation = jest
.fn()
.mockImplementationOnce(() => {
throw new HttpError({
message: 'rate limited',
statusCode: 429,
failureKind: 'rate_limited',
retryAfterSeconds: 30
})
})
.mockResolvedValueOnce('ok')
const result = await service.executeWithAuthStrategy(mockParams, queries, operation)
expect(result).toBe('ok')
expect(operation).toHaveBeenCalledTimes(2)
expect(mockAuthManager.reportAuthFailure).toHaveBeenCalledTimes(1)
expect(mockAuthManager.reportAuthFailure).toHaveBeenCalledWith(
expect.objectContaining({
user: 'managed_1',
password: 'pass_1',
failureKind: 'rate_limited',
retryAfterSeconds: 30
})
)
})
it('should not collapse attempted credentials when usernames or passwords contain colons', async () => {
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'gelbooru.com',
total: 2,
available: 2,
disabled: 0,
cooldown: 0,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential
.mockResolvedValueOnce({ user: 'name:one', password: 'pass' })
.mockResolvedValueOnce({ user: 'name', password: 'one:pass' })
const queries = { ...baseQueries } as booruQueriesDTO
const operation = jest.fn().mockImplementation(() => {
throw new HttpError({
message: 'rate limited',
statusCode: 429,
failureKind: 'rate_limited'
})
})
await expect(service.executeWithAuthStrategy(mockParams, queries, operation)).rejects.toEqual(
expect.objectContaining<Partial<ManagedCredentialPoolUnavailableError>>({
name: 'ManagedCredentialPoolUnavailableError'
})
)
expect(operation).toHaveBeenCalledTimes(2)
expect(mockAuthManager.reportAuthFailure).toHaveBeenCalledTimes(2)
})
it('should sanitize credential-bearing upstream errors before reporting managed auth failures', async () => {
const queries = { ...baseQueries } as booruQueriesDTO
const operation = jest.fn().mockImplementation(() => {
throw new HttpError({
message:
'HTTP 429 for https://gelbooru.com/index.php?page=dapi&auth_user=managed_1&auth_pass=pass_1&api_key=secret-key&user_id=123',
statusCode: 429,
failureKind: 'rate_limited'
})
})
await expect(service.executeWithAuthStrategy(mockParams, queries, operation)).rejects.toEqual(
expect.objectContaining<Partial<ManagedCredentialPoolUnavailableError>>({
name: 'ManagedCredentialPoolUnavailableError'
})
)
const reportedError = mockAuthManager.reportAuthFailure.mock.calls[0]?.[0].error
expect(reportedError).toContain('auth_user=REDACTED')
expect(reportedError).toContain('auth_pass=REDACTED')
expect(reportedError).toContain('api_key=REDACTED')
expect(reportedError).toContain('user_id=REDACTED')
expect(reportedError).not.toContain('managed_1')
expect(reportedError).not.toContain('pass_1')
expect(reportedError).not.toContain('secret-key')
})
it('should fallback to unauthenticated execution when no managed credentials are configured', async () => {
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'rule34.paheal.net',
total: 0,
available: 0,
disabled: 0,
cooldown: 0,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential.mockResolvedValue(null)
const queries = {
...baseQueries,
baseEndpoint: 'https://rule34.paheal.net'
} as booruQueriesDTO
const operation = jest.fn().mockResolvedValue('ok-no-auth')
const result = await service.executeWithAuthStrategy(mockParams, queries, operation)
expect(result).toBe('ok-no-auth')
expect(operation).toHaveBeenCalledTimes(1)
expect(mockAuthManager.reportAuthFailure).not.toHaveBeenCalled()
})
it('should throw pool unavailable error when managed credentials are exhausted', async () => {
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'gelbooru.com',
total: 1,
available: 0,
disabled: 1,
cooldown: 1,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential.mockResolvedValue(null)
mockAuthManager.getMinCooldownSeconds.mockReturnValue(42)
const queries = { ...baseQueries } as booruQueriesDTO
await expect(service.executeWithAuthStrategy(mockParams, queries, async () => 'unused')).rejects.toEqual(
expect.objectContaining<Partial<ManagedCredentialPoolUnavailableError>>({
name: 'ManagedCredentialPoolUnavailableError',
retryAfterSeconds: 42,
reason: 'cooldown_exhausted'
})
)
})
it('should treat BOORU_MANAGED_RETRY_CAP as total attempt cap', async () => {
mockConfigService.get.mockImplementation((key: string) => {
if (key === 'BOORU_MANAGED_RETRY_CAP') {
return '1'
}
return undefined
})
mockAuthManager.getDomainStats.mockReturnValue({
domain: 'gelbooru.com',
total: 3,
available: 3,
disabled: 0,
cooldown: 0,
permanentDisabled: 0
})
mockAuthManager.reserveAvailableCredential.mockResolvedValue({ user: 'managed_1', password: 'pass_1' })
const queries = { ...baseQueries } as booruQueriesDTO
const operation = jest.fn().mockImplementation(() => {
throw new HttpError({
message: 'rate limited',
statusCode: 429,
failureKind: 'rate_limited',
retryAfterSeconds: 10
})
})
await expect(service.executeWithAuthStrategy(mockParams, queries, operation)).rejects.toEqual(
expect.objectContaining<Partial<ManagedCredentialPoolUnavailableError>>({
name: 'ManagedCredentialPoolUnavailableError'
})
)
expect(operation).toHaveBeenCalledTimes(1)
expect(mockAuthManager.reportAuthFailure).toHaveBeenCalledTimes(1)
})
})
})