From 20d2bd8fe612e0acb571c3ce5767d1128c4ec681 Mon Sep 17 00:00:00 2001 From: Alejandro Akbal <37181533+AlejandroAkbal@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:33:48 +0700 Subject: [PATCH] fix(booru): back off on auth failures instead of retiring credentials instantly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An edge 403 (WAF/CDN) is indistinguishable from a genuine ban at the HTTP layer, so a single blocked window retired the whole pool: on 2026-10-05 a two-second burst of Cloudflare 403s permanently disabled 34 of 36 rule34.xxx credentials and the API answered 503 until the process was restarted — the disabled state is in-memory only and nothing ever cleared it. Non-rate-limit failures now escalate a cooldown (30s, 60s, 120s, 240s, capped at 15m) and retire a credential only after 5 consecutive failures inside a 15-minute window. Strikes expire with the window, so a credential that serves successfully in between starts from zero. 429 handling is unchanged. --- .../booru-auth-manager.service.spec.ts | 101 +++++++++++++++++- .../services/booru-auth-manager.service.ts | 87 ++++++++++++--- 2 files changed, 169 insertions(+), 19 deletions(-) diff --git a/src/booru/services/booru-auth-manager.service.spec.ts b/src/booru/services/booru-auth-manager.service.spec.ts index c77f1ec..f10b9cd 100644 --- a/src/booru/services/booru-auth-manager.service.spec.ts +++ b/src/booru/services/booru-auth-manager.service.spec.ts @@ -247,8 +247,8 @@ describe('BooruAuthManagerService', () => { total: 2, available: 1, disabled: 1, - cooldown: 0, - permanentDisabled: 1 + cooldown: 1, + permanentDisabled: 0 }) }) @@ -268,8 +268,8 @@ describe('BooruAuthManagerService', () => { total: 2, available: 0, disabled: 2, - cooldown: 0, - permanentDisabled: 2 + cooldown: 2, + permanentDisabled: 0 }) }) @@ -648,6 +648,97 @@ describe('BooruAuthManagerService', () => { expect(snapshots).toHaveLength(1) expect(snapshot?.domain).toBe('gelbooru.com') expect(credential?.user).toBe('gel-user') - expect(credential?.state).toBe('permanent') + // A lone edge 403 must not retire the credential — it only backs it off. + expect(credential?.state).toBe('cooldown') + }) + + describe('auth failure backoff', () => { + const forbiddenFailure = () => ({ + domain: 'rule34.xxx', + user: 'canonical-user', + password: 'canonical-pass', + error: 'request to https://rule34.xxx/index.php failed, status: 403', + timestamp: new Date() + }) + + function currentCredential(): DisabledCredential | undefined { + return service.getDisabledCredentials().find((credential) => credential.domain === 'rule34.xxx') + } + + function cooldownSecondsOf(credential: DisabledCredential | undefined): number { + if (credential?.state !== 'cooldown') { + throw new Error(`expected a cooldown credential, received ${String(credential?.state)}`) + } + + return (credential.cooldownUntil.getTime() - credential.disabledAt.getTime()) / 1000 + } + + function advancePastCooldown(): void { + const credential = currentCredential() + + if (credential?.state === 'cooldown') { + jest.setSystemTime(credential.cooldownUntil.getTime() + 1) + } + } + + beforeEach(() => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it('backs off an edge 403 instead of permanently disabling the credential', () => { + service.reportAuthFailure(forbiddenFailure()) + + const stats = service.getDomainStats('rule34.xxx') + + expect(currentCredential()?.state).toBe('cooldown') + expect(stats.permanentDisabled).toBe(0) + expect(stats.cooldown).toBe(1) + }) + + it('escalates the cooldown while the failures continue', () => { + service.reportAuthFailure(forbiddenFailure()) + const firstCooldownSeconds = cooldownSecondsOf(currentCredential()) + + advancePastCooldown() + service.reportAuthFailure(forbiddenFailure()) + const secondCooldownSeconds = cooldownSecondsOf(currentCredential()) + + expect(currentCredential()?.state).toBe('cooldown') + expect(secondCooldownSeconds).toBeGreaterThan(firstCooldownSeconds) + }) + + it('retires the credential only once the failures keep repeating', () => { + let permanentAfterAttempts = 0 + + for (let attempt = 1; attempt <= 12; attempt += 1) { + service.reportAuthFailure(forbiddenFailure()) + + if (currentCredential()?.state === 'permanent') { + permanentAfterAttempts = attempt + break + } + + advancePastCooldown() + } + + expect(permanentAfterAttempts).toBeGreaterThan(1) + expect(service.getDomainStats('rule34.xxx').permanentDisabled).toBe(1) + }) + + it('forgets failures that fall outside the strike window', () => { + service.reportAuthFailure(forbiddenFailure()) + advancePastCooldown() + jest.setSystemTime(Date.now() + 16 * 60 * 1_000) + + service.reportAuthFailure(forbiddenFailure()) + + expect(service.getDomainStats('rule34.xxx').permanentDisabled).toBe(0) + expect(currentCredential()?.state).toBe('cooldown') + }) }) }) diff --git a/src/booru/services/booru-auth-manager.service.ts b/src/booru/services/booru-auth-manager.service.ts index ec3022c..b6a56d9 100644 --- a/src/booru/services/booru-auth-manager.service.ts +++ b/src/booru/services/booru-auth-manager.service.ts @@ -29,8 +29,19 @@ interface ReservationResponse { export class BooruAuthManagerService implements OnModuleInit { private static readonly HTTP_STATUS_PATTERN = /(?:status(?:\s*code|_code)?|http)\s*[:=]?\s*(\d{3})|\b(\d{3})\b/i private static readonly IPC_RESERVATION_TIMEOUT_MS = 1_000 + /** + * Consecutive non-rate-limit failures tolerated before a credential is retired. + * A 403 from an edge (WAF/CDN) is indistinguishable from a genuine ban at the HTTP layer, + * so a single blocked window must never retire a credential that still works. + */ + private static readonly AUTH_FAILURE_STRIKE_THRESHOLD = 5 + /** Strikes older than this window stop counting — the credential proved itself in between. */ + private static readonly AUTH_FAILURE_STRIKE_WINDOW_MS = 15 * 60 * 1_000 + private static readonly AUTH_FAILURE_BACKOFF_BASE_SECONDS = 30 + private static readonly AUTH_FAILURE_BACKOFF_MAX_SECONDS = 15 * 60 private readonly disabledCredentials = new Map() + private readonly authFailureStrikes = new Map() private readonly cooldownCredentials = new Map< string, { disabledAt: number; cooldownUntil: number; reason: string } @@ -187,13 +198,7 @@ export class BooruAuthManagerService implements OnModuleInit { } const isRateLimit = failureKind === 'rate_limited' - const fallbackCooldownSeconds = this.getRateLimitFallbackSeconds( - normalizedDomain, - authFailure.user, - authFailure.password - ) - const cooldownSeconds = Math.max(1, authFailure.retryAfterSeconds ?? fallbackCooldownSeconds) - const cooldownUntil = new Date(Date.now() + cooldownSeconds * 1000) + const credentialKey = createCredentialKey(normalizedDomain, authFailure.user, authFailure.password) const baseCredential = { domain: normalizedDomain, user: authFailure.user, @@ -202,22 +207,52 @@ export class BooruAuthManagerService implements OnModuleInit { ...(authFailure.password !== undefined ? { password: authFailure.password } : {}) } - const disabledCredential: DisabledCredential = isRateLimit - ? { + let disabledCredential: DisabledCredential + let action: string + + if (isRateLimit) { + const fallbackCooldownSeconds = this.getRateLimitFallbackSeconds( + normalizedDomain, + authFailure.user, + authFailure.password + ) + const cooldownSeconds = Math.max(1, authFailure.retryAfterSeconds ?? fallbackCooldownSeconds) + + disabledCredential = { + ...baseCredential, + state: 'cooldown', + cooldownUntil: new Date(Date.now() + cooldownSeconds * 1000) + } + action = `cooldown for ${cooldownSeconds}s` + } else { + // A 403/401 coming from an edge (WAF/CDN) looks identical to a real ban, so back off with + // an escalating cooldown instead of retiring the credential on first sight. Only repeated, + // closely-spaced failures count as proof that the credential itself is dead. + const strikes = this.recordAuthFailureStrike(credentialKey) + + if (strikes >= BooruAuthManagerService.AUTH_FAILURE_STRIKE_THRESHOLD) { + this.authFailureStrikes.delete(credentialKey) + disabledCredential = { ...baseCredential, - state: 'cooldown', - cooldownUntil + state: 'permanent' } - : { + action = `permanently disabled after ${strikes} consecutive failures` + } else { + const backoffSeconds = this.getAuthFailureBackoffSeconds(strikes) + + disabledCredential = { ...baseCredential, - state: 'permanent' + state: 'cooldown', + cooldownUntil: new Date(Date.now() + backoffSeconds * 1000) } + action = `cooldown for ${backoffSeconds}s (failure ${strikes}/${BooruAuthManagerService.AUTH_FAILURE_STRIKE_THRESHOLD})` + } + } this.disableCredentialLocally(disabledCredential) this.broadcastDisabledCredential(disabledCredential) const stats = this.getDomainStats(normalizedDomain) - const action = isRateLimit ? `cooldown for ${cooldownSeconds}s` : 'permanently disabled' console.error(`❌ Auth failure for ${normalizedDomain}:${sanitizedUser} - ${sanitizedError} (${action})`) console.warn( @@ -735,6 +770,30 @@ export class BooruAuthManagerService implements OnModuleInit { return null } + /** + * Counts consecutive non-rate-limit failures for one credential. Strikes expire after + * AUTH_FAILURE_STRIKE_WINDOW_MS, so a credential that serves successfully again in between + * restarts from zero instead of accumulating towards retirement forever. + */ + private recordAuthFailureStrike(credentialKey: string): number { + const now = Date.now() + const previous = this.authFailureStrikes.get(credentialKey) + const strikes = + previous !== undefined && now - previous.lastFailureAt <= BooruAuthManagerService.AUTH_FAILURE_STRIKE_WINDOW_MS + ? previous.strikes + 1 + : 1 + + this.authFailureStrikes.set(credentialKey, { strikes, lastFailureAt: now }) + + return strikes + } + + private getAuthFailureBackoffSeconds(strikes: number): number { + const exponentialSeconds = BooruAuthManagerService.AUTH_FAILURE_BACKOFF_BASE_SECONDS * 2 ** Math.max(0, strikes - 1) + + return Math.min(exponentialSeconds, BooruAuthManagerService.AUTH_FAILURE_BACKOFF_MAX_SECONDS) + } + private getRateLimitFallbackSeconds(domain: string, user: string, password?: string): number { const credential = (this.authConfig[domain] ?? []).find( (candidate) => candidate.user === user && (password === undefined || candidate.password === password)