Repository navigation
fix(booru): back off on auth failures instead of retiring credentials instantly #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<string, { disabledAt: number; reason: string }>() | ||
| private readonly authFailureStrikes = new Map<string, { strikes: number; lastFailureAt: number }>() | ||
| 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 }) | ||
|
Comment on lines
+781
to
+786
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: sed -n '185,260p' src/booru/services/booru-auth-manager.service.ts
sed -n '765,805p' src/booru/services/booru-auth-manager.service.ts
sed -n '650,745p' src/booru/services/booru-auth-manager.service.spec.tsRepository: Rule-34/API Length of output: 7877 🏁 Script executed: set -o pipefail
printf '%s\n' '--- relevant declarations and usages ---'
rg -n -F --glob '*.ts' -e 'AUTH_FAILURE_STRIKE' -e 'authFailureStrikes' -e 'recordAuthFailureStrike' -e 'reportAuthFailure' -e 'reportAuthSuccess' -e 'resolveFailureKind' -e 'disableCredentialLocally' src/booru || test "$?" -eq 1
printf '%s\n' '--- service declarations ---'
sed -n '1,190p' src/booru/services/booru-auth-manager.service.ts
printf '%s\n' '--- failure and adjacent lifecycle methods ---'
sed -n '185,285p' src/booru/services/booru-auth-manager.service.ts
printf '%s\n' '--- strike-related block ---'
sed -n '730,810p' src/booru/services/booru-auth-manager.service.ts
printf '%s\n' '--- all backoff/strike tests ---'
rg -n -F --glob '*.spec.ts' -e 'auth failure backoff' -e 'strike window' -e 'permanently' -e 'consecutive' -e '16 * 60' src/booru || test "$?" -eq 1
printf '%s\n' '--- documentation/config references ---'
rg -n -i --glob '!node_modules/**' --glob '!dist/**' -e 'five failures' -e '5 failures' -e '15-minute' -e '15 minute' -e 'strike window' -e 'auth failure' -e 'credential' docs src README.md .github 2>/dev/null || test "$?" -eq 1
printf '%s\n' '--- PR diff for relevant file ---'
git diff --unified=25 859b11f132b3a0a3ebf119edad2f3ca2fb5754c7 20d2bd8fe612e0acb571c3ce5767d1128c4ec681 -- src/booru/services/booru-auth-manager.service.ts src/booru/services/booru-auth-manager.service.spec.tsRepository: Rule-34/API Length of output: 41364 🏁 Script executed: set -o pipefail
printf '%s\n' '--- failure entrypoint ---'
sed -n '210,275p' src/booru/interceptors/booru-exception.interceptor.ts
sed -n '265,305p' src/booru/booru.service.ts
printf '%s\n' '--- exact strike-related tests with line numbers ---'
nl -ba src/booru/services/booru-auth-manager.service.spec.ts | sed -n '675,755p'
printf '%s\n' '--- exact implementation with line numbers ---'
nl -ba src/booru/services/booru-auth-manager.service.ts | sed -n '25,50p;185,260p;768,795p'
printf '%s\n' '--- commit metadata ---'
git show -s --format=fuller 20d2bd8fe612e0acb571c3ce5767d1128c4ec681
printf '%s\n' '--- exact repository documentation references ---'
rg -n -i --glob '!node_modules/**' --glob '!dist/**' -e 'five failures' -e '5 failures' -e '15-minute' -e '15 minute' -e 'strike window' -e 'auth failure' -e 'credential' . 2>/dev/null | sed -n '1,160p' || test "${PIPESTATUS[0]}" -eq 1Repository: Rule-34/API Length of output: 31945 Anchor the strike window at the first failure.
Suggested fix- private readonly authFailureStrikes = new Map<string, { strikes: number; lastFailureAt: number }>()
+ private readonly authFailureStrikes = new Map<string, { strikes: number; firstFailureAt: number }>()
private recordAuthFailureStrike(credentialKey: string): number {
const now = Date.now()
const previous = this.authFailureStrikes.get(credentialKey)
+ const withinWindow =
+ previous !== undefined && now - previous.firstFailureAt <= BooruAuthManagerService.AUTH_FAILURE_STRIKE_WINDOW_MS
const strikes =
- previous !== undefined && now - previous.lastFailureAt <= BooruAuthManagerService.AUTH_FAILURE_STRIKE_WINDOW_MS
+ withinWindow && previous !== undefined
? previous.strikes + 1
: 1
- this.authFailureStrikes.set(credentialKey, { strikes, lastFailureAt: now })
+ this.authFailureStrikes.set(credentialKey, {
+ strikes,
+ firstFailureAt: withinWindow && previous !== undefined ? previous.firstFailureAt : now
+ })
return strikes
}🤖 Prompt for AI Agents |
||
|
|
||
| return strikes | ||
| } | ||
|
Comment on lines
+778
to
+789
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: #!/bin/bash
rg -nP 'authFailureStrikes|reportAuth(Success|Ok)|resetAuthFailure|markCredentialSuccess' srcRepository: Rule-34/API Length of output: 660 🏁 Script executed: #!/bin/bash
set -e
nl -ba src/booru/services/booru-auth-manager.service.ts | sed -n '1,280p'
printf '\n--- strike method and surrounding declarations ---\n'
nl -ba src/booru/services/booru-auth-manager.service.ts | sed -n '730,820p'
printf '\n--- relevant callers and request flow ---\n'
rg -n -F --glob '*.ts' -e 'recordAuthFailureStrike' -e 'handleAuthenticationFailure' -e 'authFailureStrikes.delete' -e 'getCredential' -e 'request' src/booruRepository: Rule-34/API Length of output: 30946 🏁 Script executed: nl -ba src/booru/services/booru-auth-manager.service.ts | sed -n '1,280p'
printf '\n--- strike method ---\n'
nl -ba src/booru/services/booru-auth-manager.service.ts | sed -n '730,820p'
printf '\n--- callers and flow ---\n'
rg -n -F --glob '*.ts' -e 'recordAuthFailureStrike' -e 'handleAuthenticationFailure' -e 'authFailureStrikes.delete' -e 'getCredential' -e 'axios' src/booruRepository: Rule-34/API Length of output: 18541 Reset the strike count after a successful booru request.
Add a success hook on the booru request completion path that calls 🤖 Prompt for AI Agents |
||
|
|
||
| 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) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: Rule-34/API
Length of output: 5967
Assert the exact retirement attempt.
The test retires the credential after repeated failures, but
permanentAfterAttempts > 1would also pass if retirement occurred after two strikes. Assert the five-strike contract directly.Suggested fix
📝 Committable suggestion
🤖 Prompt for AI Agents