diff --git a/.env.example b/.env.example index 82187aa..522860e 100644 --- a/.env.example +++ b/.env.example @@ -13,4 +13,4 @@ SENTRY_DSN= # For downloading private packages GITHUB_TOKEN= -BOORU_AUTH_CONFIG='{"gelbooru.com": [{ "user": "001", "password": "28484nf82" } ]}' \ No newline at end of file +BOORU_AUTH_CONFIG='{"gelbooru.com":[{"user":"001","password":"gelbooru-api-key","rateLimit":{"requests":10,"windowSeconds":1}}],"rule34.xxx":[{"user":"002","password":"rule34-api-key","rateLimit":{"requests":60,"windowSeconds":60}}]}' diff --git a/src/booru/booru-auth.live.spec.ts b/src/booru/booru-auth.live.spec.ts new file mode 100644 index 0000000..c70c83b --- /dev/null +++ b/src/booru/booru-auth.live.spec.ts @@ -0,0 +1,140 @@ +import type { TestingModule } from '@nestjs/testing' +import { Test } from '@nestjs/testing' +import { ConfigModule, ConfigService } from '@nestjs/config' +import { BooruTypesStringEnum } from '@alejandroakbal/universal-booru-wrapper' +import { BooruService, ManagedCredentialPoolUnavailableError } from './booru.service' +import type { booruQueryValuesPostsDTO } from './dto/booru-queries.dto' +import { BooruAuthManagerService } from './services/booru-auth-manager.service' +import { SENSITIVE_AUTH_PARAMS } from './constants/sensitive-auth-params' + +const runLiveTests = process.env['RUN_BOORU_AUTH_LIVE_TESTS'] === 'true' +const describeLive = runLiveTests ? describe : describe.skip +const sensitiveAuthParams = SENSITIVE_AUTH_PARAMS + +const liveBoorus: { + domain: string + booruType: BooruTypesStringEnum + initialPageID: number +}[] = [ + { + domain: 'gelbooru.com', + booruType: BooruTypesStringEnum.GELBOORU_COM, + initialPageID: 0 + }, + { + domain: 'rule34.xxx', + booruType: BooruTypesStringEnum.RULE_34_XXX, + initialPageID: 0 + } +] + +function sanitizeLiveSmokeErrorMessage(message: string): string { + let sanitizedMessage = message + + for (const key of sensitiveAuthParams) { + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + sanitizedMessage = sanitizedMessage.replace(new RegExp(`([?&\\s]${escapedKey}=)[^\\s&#]+`, 'gi'), '$1REDACTED') + } + + return sanitizedMessage +} + +describe('live smoke error sanitization', () => { + it('redacts auth query params before rethrowing non-quota live errors', () => { + const message = + 'HTTP 403 https://gelbooru.com/index.php?page=dapi&api_key=secret&user_id=123 auth_user=user auth_pass=pass' + + const sanitizedMessage = sanitizeLiveSmokeErrorMessage(message) + + expect(sanitizedMessage).toContain('api_key=REDACTED') + expect(sanitizedMessage).toContain('user_id=REDACTED') + expect(sanitizedMessage).toContain('auth_user=REDACTED') + expect(sanitizedMessage).toContain('auth_pass=REDACTED') + expect(sanitizedMessage).not.toContain('secret') + expect(sanitizedMessage).not.toContain('user_id=123') + expect(sanitizedMessage).not.toContain('auth_pass=pass') + }) +}) + +describeLive('authenticated booru live smoke tests', () => { + let module: TestingModule + let service: BooruService + + beforeAll(async () => { + module = await Test.createTestingModule({ + imports: [ConfigModule.forRoot({ isGlobal: true, cache: false })], + providers: [BooruService, BooruAuthManagerService, ConfigService] + }).compile() + + service = module.get(BooruService) + module.get(BooruAuthManagerService).onModuleInit() + }) + + afterAll(async () => { + await module.close() + }) + + it.each(liveBoorus)( + 'returns normalized posts for $domain with configured auth', + async (booru: (typeof liveBoorus)[number]) => { + const queries = { + baseEndpoint: booru.domain, + limit: 1, + pageID: booru.initialPageID + } as booruQueryValuesPostsDTO + + let posts: { id?: unknown }[] + + try { + posts = await service.executeWithAuthStrategy<{ id?: unknown }[]>( + { booruType: booru.booruType }, + queries, + (api) => + api.getPosts({ + limit: 1, + pageID: booru.initialPageID + }) + ) + } catch (error) { + if (error instanceof ManagedCredentialPoolUnavailableError && error.reason === 'cooldown_exhausted') { + console.warn( + JSON.stringify({ + domain: booru.domain, + booruType: booru.booruType, + status: 'quota_exhausted', + retryAfterSeconds: error.retryAfterSeconds + }) + ) + return + } + + const message = error instanceof Error ? error.message : String(error) + const sanitizedMessage = sanitizeLiveSmokeErrorMessage(message) + + if (error instanceof Error) { + error.message = sanitizedMessage + + if (error.stack !== undefined) { + error.stack = sanitizeLiveSmokeErrorMessage(error.stack) + } + } + + throw new Error(sanitizedMessage, { cause: error }) + } + + expect(posts.length).toBeGreaterThan(0) + + const firstPost = posts[0] + + expect(firstPost?.id).toBeDefined() + + console.log( + JSON.stringify({ + domain: booru.domain, + booruType: booru.booruType, + itemCount: posts.length + }) + ) + } + ) +}) diff --git a/src/booru/booru.service.spec.ts b/src/booru/booru.service.spec.ts index d224f3e..8d9fec9 100644 --- a/src/booru/booru.service.spec.ts +++ b/src/booru/booru.service.spec.ts @@ -9,7 +9,7 @@ import type { BooruEndpointParamsDTO } from './dto/request-booru.dto' import { BooruAuthManagerService } from './services/booru-auth-manager.service' interface MockAuthManager { - getAvailableCredential: jest.MockedFunction + reserveAvailableCredential: jest.MockedFunction getDomainStats: jest.MockedFunction reportAuthFailure: jest.MockedFunction getMinCooldownSeconds: jest.MockedFunction @@ -48,7 +48,9 @@ describe('BooruService', () => { beforeEach(async () => { mockAuthManager = { - getAvailableCredential: jest.fn() as jest.MockedFunction, + reserveAvailableCredential: jest.fn() as jest.MockedFunction< + BooruAuthManagerService['reserveAvailableCredential'] + >, getDomainStats: jest.fn() as jest.MockedFunction, reportAuthFailure: jest.fn() as jest.MockedFunction, getMinCooldownSeconds: jest.fn() as jest.MockedFunction @@ -80,6 +82,7 @@ describe('BooruService', () => { cooldown: 0, permanentDisabled: 0 }) + mockAuthManager.reserveAvailableCredential.mockResolvedValue({ user: 'managed_1', password: 'pass_1' }) }) describe('Authentication Resolution', () => { @@ -96,16 +99,13 @@ describe('BooruService', () => { expect(getApiAuth(api)?.apiKey).toBe('query_pass') }) - it('should fallback to environment variables when query parameters are missing or incomplete', () => { - mockAuthManager.getAvailableCredential.mockReturnValue({ user: 'env_user', password: 'env_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(mockAuthManager.getAvailableCredential).toHaveBeenCalledWith('https://gelbooru.com') - expect(getApiAuth(apiNoAuth)?.username).toBe('env_user') - expect(getApiAuth(apiNoAuth)?.apiKey).toBe('env_pass') + expect(getApiAuth(apiNoAuth)?.username).toBeUndefined() + expect(getApiAuth(apiNoAuth)?.apiKey).toBeUndefined() // Test with partial query params (should still use env) const queriesPartial = { @@ -114,13 +114,11 @@ describe('BooruService', () => { } as booruQueriesDTO const apiPartial = service.buildApiClass(mockParams, queriesPartial) - expect(getApiAuth(apiPartial)?.username).toBe('env_user') - expect(getApiAuth(apiPartial)?.apiKey).toBe('env_pass') + expect(getApiAuth(apiPartial)?.username).toBeUndefined() + expect(getApiAuth(apiPartial)?.apiKey).toBeUndefined() }) - it('should prioritize query parameters over environment variables', () => { - mockAuthManager.getAvailableCredential.mockReturnValue({ user: 'env_user', password: 'env_pass' }) - + it('should use query parameters when building metadata APIs', () => { const queries = { ...baseQueries, auth_user: 'query_user', @@ -129,39 +127,25 @@ describe('BooruService', () => { const api = service.buildApiClass(mockParams, queries) - // Should use query credentials, not env credentials - auth manager should not be called - expect(mockAuthManager.getAvailableCredential).not.toHaveBeenCalled() expect(getApiAuth(api)?.username).toBe('query_user') expect(getApiAuth(api)?.apiKey).toBe('query_pass') }) - it('should create API without authentication when no credentials are available', () => { - mockAuthManager.getAvailableCredential.mockReturnValue(null) - + 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(mockAuthManager.getAvailableCredential).toHaveBeenCalledWith('https://gelbooru.com') expect(getApiAuth(api)?.username).toBeUndefined() expect(getApiAuth(api)?.apiKey).toBeUndefined() }) - it('should use auth manager for credential selection', () => { - mockAuthManager.getAvailableCredential.mockReturnValue({ user: 'managed_user', password: 'managed_pass' }) - + it('should expose selected credential metadata when building API with an auth override', () => { const queries = { ...baseQueries } as booruQueriesDTO - const api = service.buildApiClass(mockParams, queries) - - expect(mockAuthManager.getAvailableCredential).toHaveBeenCalledWith('https://gelbooru.com') - expect(getApiAuth(api)?.username).toBe('managed_user') - expect(getApiAuth(api)?.apiKey).toBe('managed_pass') - }) - - it('should expose selected credential metadata when building API with context', () => { - mockAuthManager.getAvailableCredential.mockReturnValue({ user: 'managed_user', password: 'managed_pass' }) - - const queries = { ...baseQueries } as booruQueriesDTO - const result = service.buildApiWithContext(mockParams, queries) + 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') @@ -171,6 +155,15 @@ describe('BooruService', () => { }) }) + 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, @@ -185,7 +178,6 @@ describe('BooruService', () => { user: 'query_user', password: 'query_pass' }) - expect(mockAuthManager.getAvailableCredential).not.toHaveBeenCalled() }) }) @@ -201,7 +193,6 @@ describe('BooruService', () => { const result = await service.executeWithAuthStrategy(mockParams, queries, operation) expect(result).toBe('ok') - expect(mockAuthManager.getAvailableCredential).not.toHaveBeenCalled() expect(mockAuthManager.reportAuthFailure).not.toHaveBeenCalled() }) @@ -215,9 +206,9 @@ describe('BooruService', () => { permanentDisabled: 0 }) - mockAuthManager.getAvailableCredential - .mockReturnValueOnce({ user: 'managed_1', password: 'pass_1' }) - .mockReturnValueOnce({ user: 'managed_2', password: 'pass_2' }) + mockAuthManager.reserveAvailableCredential + .mockResolvedValueOnce({ user: 'managed_1', password: 'pass_1' }) + .mockResolvedValueOnce({ user: 'managed_2', password: 'pass_2' }) const queries = { ...baseQueries } as booruQueriesDTO const operation = jest @@ -247,6 +238,67 @@ describe('BooruService', () => { ) }) + 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>({ + 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>({ + 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', @@ -256,7 +308,7 @@ describe('BooruService', () => { cooldown: 0, permanentDisabled: 0 }) - mockAuthManager.getAvailableCredential.mockReturnValue(null) + mockAuthManager.reserveAvailableCredential.mockResolvedValue(null) const queries = { ...baseQueries, @@ -270,7 +322,6 @@ describe('BooruService', () => { expect(result).toBe('ok-no-auth') expect(operation).toHaveBeenCalledTimes(1) expect(mockAuthManager.reportAuthFailure).not.toHaveBeenCalled() - expect(mockAuthManager.getAvailableCredential).toHaveBeenCalledWith('https://rule34.paheal.net') }) it('should throw pool unavailable error when managed credentials are exhausted', async () => { @@ -282,7 +333,7 @@ describe('BooruService', () => { cooldown: 1, permanentDisabled: 0 }) - mockAuthManager.getAvailableCredential.mockReturnValue(null) + mockAuthManager.reserveAvailableCredential.mockResolvedValue(null) mockAuthManager.getMinCooldownSeconds.mockReturnValue(42) const queries = { ...baseQueries } as booruQueriesDTO @@ -314,7 +365,7 @@ describe('BooruService', () => { permanentDisabled: 0 }) - mockAuthManager.getAvailableCredential.mockReturnValue({ user: 'managed_1', password: 'pass_1' }) + mockAuthManager.reserveAvailableCredential.mockResolvedValue({ user: 'managed_1', password: 'pass_1' }) const queries = { ...baseQueries } as booruQueriesDTO const operation = jest.fn().mockImplementation(() => { diff --git a/src/booru/booru.service.ts b/src/booru/booru.service.ts index 7a24b57..095dbd4 100644 --- a/src/booru/booru.service.ts +++ b/src/booru/booru.service.ts @@ -21,6 +21,7 @@ import { booruQueriesDTO } from './dto/booru-queries.dto' import { BooruEndpointParamsDTO } from './dto/request-booru.dto' import type { AuthFailureEvent } from './interfaces/auth-manager.interface' import { BooruAuthManagerService } from './services/booru-auth-manager.service' +import { SENSITIVE_AUTH_PARAMS } from './constants/sensitive-auth-params' export interface ResolvedAuthCredentials { auth?: { username: string; apiKey: string } @@ -53,13 +54,15 @@ export class ManagedCredentialPoolUnavailableError extends Error { @Injectable() export class BooruService { + private readonly sensitiveAuthParams = new Set(SENSITIVE_AUTH_PARAMS) + constructor( private readonly configService: ConfigService, private readonly authManager: BooruAuthManagerService ) {} public buildApiClass(params: BooruEndpointParamsDTO, queries: booruQueriesDTO): BooruTypes { - return this.buildApiWithContext(params, queries).api + return this.buildApiWithContext(params, queries, this.resolveQueryAuthCredentials(queries)).api } public async executeWithAuthStrategy( @@ -68,14 +71,18 @@ export class BooruService { operation: (api: BooruTypes, authResolution: ResolvedAuthCredentials) => Promise ): Promise { if (this.hasQueryCredentials(queries)) { - const explicitContext = this.buildApiWithContext(params, queries) + const explicitContext = this.buildApiWithContext(params, queries, this.resolveQueryAuthCredentials(queries)) return operation(explicitContext.api, explicitContext.authResolution) } return this.executeManagedCredentialFailover(params, queries, operation) } - public buildApiWithContext(params: BooruEndpointParamsDTO, queries: booruQueriesDTO): BuiltBooruApi { + public buildApiWithContext( + params: BooruEndpointParamsDTO, + queries: booruQueriesDTO, + resolvedAuthOverride?: ResolvedAuthCredentials + ): BuiltBooruApi { const booruClass = this.getApiClassByType(params.booruType) const endpoints: IBooruEndpoints = { @@ -156,8 +163,7 @@ export class BooruService { // No default QueryValues are needed - // Resolve authentication credentials - const authResolution = this.resolveAuthCredentials(queries) + const authResolution = resolvedAuthOverride ?? this.resolveQueryAuthCredentials(queries) const options: Partial = {} @@ -182,39 +188,21 @@ export class BooruService { } } - private resolveAuthCredentials(queries: booruQueriesDTO): ResolvedAuthCredentials { - // Priority 1: Query parameters - if (this.hasQueryCredentials(queries)) { - return { - auth: { - username: queries.auth_user, - apiKey: queries.auth_pass - }, - source: 'query', - selectedCredential: { - user: queries.auth_user, - password: queries.auth_pass - } - } - } - - // Priority 2: Environment variables through auth manager - const envCredentials = this.authManager.getAvailableCredential(queries.baseEndpoint) - - if (envCredentials) { - return { - auth: { - username: envCredentials.user, - apiKey: envCredentials.password - }, - source: 'env', - selectedCredential: envCredentials - } + private resolveQueryAuthCredentials(queries: booruQueriesDTO): ResolvedAuthCredentials { + if (!this.hasQueryCredentials(queries)) { + return { source: 'none' } } - // Priority 3: No authentication return { - source: 'none' + auth: { + username: queries.auth_user, + apiKey: queries.auth_pass + }, + source: 'query', + selectedCredential: { + user: queries.auth_user, + password: queries.auth_pass + } } } @@ -235,14 +223,24 @@ export class BooruService { const attemptedCredentials = new Set() for (let attempt = 0; attempt < maxAttempts; attempt++) { - const context = this.buildApiWithContext(params, queries) - const selectedCredential = context.authResolution.selectedCredential + const selectedCredential = await this.authManager.reserveAvailableCredential(queries.baseEndpoint) - if (context.authResolution.source !== 'env' || !selectedCredential) { + if (!selectedCredential) { throw this.createPoolUnavailableError(queries.baseEndpoint) } - const credentialKey = `${selectedCredential.user}:${selectedCredential.password}` + const authResolution: ResolvedAuthCredentials = { + auth: { + username: selectedCredential.user, + apiKey: selectedCredential.password + }, + source: 'env', + selectedCredential + } + + const context = this.buildApiWithContext(params, queries, authResolution) + + const credentialKey = JSON.stringify([selectedCredential.user, selectedCredential.password]) if (attemptedCredentials.has(credentialKey)) { throw this.createPoolUnavailableError(queries.baseEndpoint) @@ -306,13 +304,10 @@ export class BooruService { private createPoolUnavailableError(domain: string): ManagedCredentialPoolUnavailableError { const stats = this.authManager.getDomainStats(domain) + const retryAfterSeconds = this.authManager.getMinCooldownSeconds(domain) - if (stats.available === 0 && stats.cooldown > 0) { - return new ManagedCredentialPoolUnavailableError( - domain, - 'cooldown_exhausted', - this.authManager.getMinCooldownSeconds(domain) - ) + if (retryAfterSeconds !== undefined || (stats.available === 0 && stats.cooldown > 0)) { + return new ManagedCredentialPoolUnavailableError(domain, 'cooldown_exhausted', retryAfterSeconds) } return new ManagedCredentialPoolUnavailableError(domain, 'permanent_exhausted') @@ -328,11 +323,59 @@ export class BooruService { } private stringifyHttpError(error: HttpError): string { - if (typeof error.message === 'string' && error.message.length > 0) { - return error.message + const message = typeof error.message === 'string' && error.message.length > 0 ? error.message : error.toString() + + return this.sanitizeErrorMessage(message) + } + + private sanitizeErrorMessage(message: string): string { + if (!message) { + return message + } + + const urlPattern = /https?:\/\/[^\s]+/gi + const sanitizedUrlMessage = message.replace(urlPattern, (url) => this.sanitizeUrl(url)) + return this.sanitizeKeyValueTokens(sanitizedUrlMessage) + } + + private sanitizeKeyValueTokens(message: string): string { + let sanitizedMessage = message + + for (const key of this.sensitiveAuthParams) { + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const pattern = new RegExp(`\\b(${escapedKey})(\\s*=\\s*)([^\\s&#,;\\]\\)\\}]+)`, 'gi') + sanitizedMessage = sanitizedMessage.replace(pattern, '$1$2REDACTED') + } + + return sanitizedMessage + } + + private sanitizeUrl(url: string): string { + try { + const urlObj = new URL(url) + + for (const [key] of urlObj.searchParams.entries()) { + if (this.sensitiveAuthParams.has(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.sensitiveAuthParams) { + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const pattern = new RegExp(`([?&]${escapedKey}=)[^&#\\s]*`, 'gi') + sanitizedUrl = sanitizedUrl.replace(pattern, '$1REDACTED') } - return error.toString() + return sanitizedUrl } private getFailureKind( diff --git a/src/booru/constants/booru-auth-provider-policies.ts b/src/booru/constants/booru-auth-provider-policies.ts new file mode 100644 index 0000000..858a9f4 --- /dev/null +++ b/src/booru/constants/booru-auth-provider-policies.ts @@ -0,0 +1,50 @@ +export interface RateLimitPolicy { + requests: number + windowSeconds: number +} + +export interface BooruAuthProviderPolicy { + canonicalDomain: string + aliases?: string[] + rateLimit: RateLimitPolicy +} + +export const BOORU_AUTH_PROVIDER_POLICIES: BooruAuthProviderPolicy[] = [ + { + canonicalDomain: 'gelbooru.com', + rateLimit: { requests: 10, windowSeconds: 1 } + }, + { + canonicalDomain: 'www.gelbooru.com', + rateLimit: { requests: 10, windowSeconds: 1 } + }, + { + canonicalDomain: 'rule34.xxx', + aliases: ['api.rule34.xxx', 'www.rule34.xxx'], + rateLimit: { requests: 60, windowSeconds: 60 } + } +] + +export const BOORU_AUTH_DOMAIN_ALIASES = BOORU_AUTH_PROVIDER_POLICIES.reduce>( + (aliases, policy) => { + for (const alias of policy.aliases ?? []) { + aliases[alias] = policy.canonicalDomain + } + + return aliases + }, + {} +) + +export const BOORU_AUTH_RATE_LIMIT_DEFAULTS = BOORU_AUTH_PROVIDER_POLICIES.reduce>( + (defaults, policy) => { + defaults[policy.canonicalDomain] = policy.rateLimit + + for (const alias of policy.aliases ?? []) { + defaults[alias] = policy.rateLimit + } + + return defaults + }, + {} +) diff --git a/src/booru/constants/sensitive-auth-params.ts b/src/booru/constants/sensitive-auth-params.ts index e78177e..f5fe288 100644 --- a/src/booru/constants/sensitive-auth-params.ts +++ b/src/booru/constants/sensitive-auth-params.ts @@ -1,6 +1,8 @@ export const SENSITIVE_AUTH_PARAMS = [ 'user_id', 'api_key', + 'apikey', + 'apiKey', 'password', 'password_hash', 'pass_hash', diff --git a/src/booru/interfaces/auth-manager.interface.ts b/src/booru/interfaces/auth-manager.interface.ts index c318590..c5988ed 100644 --- a/src/booru/interfaces/auth-manager.interface.ts +++ b/src/booru/interfaces/auth-manager.interface.ts @@ -1,6 +1,10 @@ export interface BooruAuthCredential { user: string password: string + rateLimit?: { + requests: number + windowSeconds: number + } } export type BooruAuthConfig = Record @@ -24,6 +28,25 @@ export interface CooldownDisabledCredential extends DisabledCredentialBase { export type DisabledCredential = PermanentDisabledCredential | CooldownDisabledCredential +interface SerializedDisabledCredentialBase { + domain: string + user: string + password?: string + disabledAt: string + reason?: string +} + +export interface SerializedPermanentDisabledCredential extends SerializedDisabledCredentialBase { + state: 'permanent' +} + +export interface SerializedCooldownDisabledCredential extends SerializedDisabledCredentialBase { + state: 'cooldown' + cooldownUntil: string +} + +export type SerializedDisabledCredential = SerializedPermanentDisabledCredential | SerializedCooldownDisabledCredential + export interface AuthCredentialStats { domain: string total: number @@ -86,7 +109,10 @@ export interface AuthFailureEvent { timestamp: Date } -export interface IpcAuthMessage { - type: 'DISABLE_CREDENTIAL' | 'CREDENTIAL_STATS_REQUEST' | 'CREDENTIAL_STATS_RESPONSE' - payload: DisabledCredential | AuthCredentialStats[] | { requestId: string } -} +export type IpcAuthMessage = + | { type: 'DISABLE_CREDENTIAL'; payload: SerializedDisabledCredential } + | { type: 'RESERVE_CREDENTIAL'; payload: { requestId: string; domain: string } } + | { + type: 'RESERVE_CREDENTIAL_RESPONSE' + payload: { requestId: string; credential: BooruAuthCredential | null; retryAfterSeconds?: number } + } diff --git a/src/booru/services/booru-auth-manager.service.spec.ts b/src/booru/services/booru-auth-manager.service.spec.ts index 3c02a84..c77f1ec 100644 --- a/src/booru/services/booru-auth-manager.service.spec.ts +++ b/src/booru/services/booru-auth-manager.service.spec.ts @@ -2,15 +2,27 @@ import type { TestingModule } from '@nestjs/testing' import { Test } from '@nestjs/testing' import { ConfigModule } from '@nestjs/config' import { BooruAuthManagerService } from './booru-auth-manager.service' -import type { CooldownDisabledCredential, DisabledCredential } from '../interfaces/auth-manager.interface' +import type { + BooruAuthCredential, + DisabledCredential, + SerializedCooldownDisabledCredential +} from '../interfaces/auth-manager.interface' interface AuthManagerPrivateAccess { disableCredentialLocally(credential: DisabledCredential): void + reserveAvailableCredentialFromPrimary(domain: string): Promise } -type SerializedCooldownDisabledCredential = Omit & { - disabledAt: string - cooldownUntil: string +async function createAuthManagerService(): Promise<{ module: TestingModule; service: BooruAuthManagerService }> { + const module = await Test.createTestingModule({ + imports: [ConfigModule.forRoot({ isGlobal: true, cache: false, ignoreEnvFile: true })], + providers: [BooruAuthManagerService] + }).compile() + + const service = module.get(BooruAuthManagerService) + service.onModuleInit() + + return { module, service } } describe('BooruAuthManagerService', () => { @@ -26,24 +38,24 @@ describe('BooruAuthManagerService', () => { { user: 'api-user', password: 'api-pass' } ], 'gelbooru.com': [{ user: 'gel-user', password: 'gel-pass' }], + 'gelbooru-override.test': [ + { user: 'override-user', password: 'override-pass', rateLimit: { requests: 2, windowSeconds: 5 } } + ], 'www.gelbooru.com': [{ user: 'www-gel-user', password: 'www-gel-pass' }], 'same-user.test': [ { user: 'shared-user', password: 'first-pass' }, { user: 'shared-user', password: 'second-pass' } ], + 'quota-round-robin.test': [ + { user: 'quota-user-1', password: 'quota-pass-1', rateLimit: { requests: 1, windowSeconds: 10 } }, + { user: 'quota-user-2', password: 'quota-pass-2', rateLimit: { requests: 2, windowSeconds: 10 } } + ], 'colon-user.test': [ { user: 'name:one', password: 'pass' }, { user: 'name', password: 'one:pass' } ] }) - - const module: TestingModule = await Test.createTestingModule({ - imports: [ConfigModule.forRoot({ isGlobal: true, cache: false, ignoreEnvFile: true })], - providers: [BooruAuthManagerService] - }).compile() - - service = module.get(BooruAuthManagerService) - service.onModuleInit() + ;({ service } = await createAuthManagerService()) }) afterEach(() => { @@ -69,16 +81,16 @@ describe('BooruAuthManagerService', () => { }) }) - it('should keep non-aliased www domains separate from root domains', () => { - const rootCredential = service.getAvailableCredential('https://gelbooru.com/index.php?page=dapi') - const wwwCredential = service.getAvailableCredential('https://www.gelbooru.com/index.php?page=dapi') + it('should keep non-aliased www domains separate from root domains', async () => { + const rootCredential = await service.reserveAvailableCredential('https://gelbooru.com/index.php?page=dapi') + const wwwCredential = await service.reserveAvailableCredential('https://www.gelbooru.com/index.php?page=dapi') expect(rootCredential).toEqual({ user: 'gel-user', password: 'gel-pass' }) expect(wwwCredential).toEqual({ user: 'www-gel-user', password: 'www-gel-pass' }) }) - it('should resolve credentials for api.rule34.xxx using rule34.xxx auth pool', () => { - const credential = service.getAvailableCredential('https://api.rule34.xxx/index.php?page=dapi') + it('should resolve credentials for api.rule34.xxx using rule34.xxx auth pool', async () => { + const credential = await service.reserveAvailableCredential('https://api.rule34.xxx/index.php?page=dapi') if (credential === null) { throw new Error('Expected a credential for api.rule34.xxx') @@ -87,8 +99,8 @@ describe('BooruAuthManagerService', () => { expect(['canonical-user', 'api-user']).toContain(credential.user) }) - it('should resolve credentials when base endpoint uses uppercase protocol', () => { - const credential = service.getAvailableCredential('HTTPS://API.RULE34.XXX/index.php?page=dapi') + it('should resolve credentials when base endpoint uses uppercase protocol', async () => { + const credential = await service.reserveAvailableCredential('HTTPS://API.RULE34.XXX/index.php?page=dapi') if (credential === null) { throw new Error('Expected a credential for uppercase api.rule34.xxx') @@ -97,8 +109,8 @@ describe('BooruAuthManagerService', () => { expect(['canonical-user', 'api-user']).toContain(credential.user) }) - it('should normalize reported auth failures to canonical rule34 domain', () => { - const selectedCredential = service.getAvailableCredential('https://rule34.xxx/index.php?page=dapi') + it('should normalize reported auth failures to canonical rule34 domain', async () => { + const selectedCredential = await service.reserveAvailableCredential('https://rule34.xxx/index.php?page=dapi') if (selectedCredential === null) { throw new Error('Expected a credential for rule34.xxx') @@ -151,7 +163,7 @@ describe('BooruAuthManagerService', () => { user: 'www-gel-user', password: 'www-gel-pass', error: - 'HTTP 403: Forbidden auth_user=www-gel-user auth_pass=secret123 token=abc123 api_key=xyz789 user_id=42 key=plain-key limit=10', + 'HTTP 403: Forbidden auth_user=www-gel-user auth_pass=secret123 token=abc123 api_key=xyz789 apikey=compact-key user_id=42 key=plain-key limit=10', timestamp: new Date() }) @@ -161,6 +173,7 @@ describe('BooruAuthManagerService', () => { expect(loggedMessage).toContain('auth_pass=REDACTED') expect(loggedMessage).toContain('token=REDACTED') expect(loggedMessage).toContain('api_key=REDACTED') + expect(loggedMessage).toContain('apikey=REDACTED') expect(loggedMessage).toContain('user_id=REDACTED') expect(loggedMessage).toContain('key=REDACTED') expect(loggedMessage).toContain('limit=10') @@ -168,12 +181,33 @@ describe('BooruAuthManagerService', () => { expect(loggedMessage).not.toContain('secret123') expect(loggedMessage).not.toContain('abc123') expect(loggedMessage).not.toContain('xyz789') + expect(loggedMessage).not.toContain('compact-key') expect(loggedMessage).not.toContain('plain-key') errorSpy.mockRestore() warnSpy.mockRestore() }) + it('should fail startup when auth config credentials have the wrong shape', async () => { + process.env['BOORU_AUTH_CONFIG'] = JSON.stringify({ + 'rule34.xxx': [{ user: 'valid-user', password: 'secret-one' }, { user: 'missing-password' }] + }) + + await expect(createAuthManagerService()).rejects.toThrow( + 'Invalid BOORU_AUTH_CONFIG credential for rule34.xxx at index 1' + ) + }) + + it('should fail startup when auth config rate limits have the wrong shape', async () => { + process.env['BOORU_AUTH_CONFIG'] = JSON.stringify({ + 'rule34.xxx': [{ user: 'valid-user', password: 'secret-one', rateLimit: { requests: 0, windowSeconds: 1 } }] + }) + + await expect(createAuthManagerService()).rejects.toThrow( + 'Invalid BOORU_AUTH_CONFIG rateLimit for rule34.xxx at index 0' + ) + }) + it('should redact malformed uppercase-protocol URLs in auth failure logs', () => { const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined) const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined) @@ -312,7 +346,125 @@ describe('BooruAuthManagerService', () => { ).toBe(true) }) - it('should reactivate credentials after cooldown expiration', () => { + it('should use provider fallback cooldown when rate limit has no retry-after', () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + service.reportAuthFailure({ + domain: 'https://gelbooru.com/index.php?page=dapi', + user: 'gel-user', + password: 'gel-pass', + error: 'HTTP 429: Too Many Requests', + failureKind: 'rate_limited', + timestamp: new Date() + }) + + const disabledCredential = service + .getDisabledCredentials() + .find((credential) => credential.domain === 'gelbooru.com' && credential.user === 'gel-user') + + expect(disabledCredential?.state).toBe('cooldown') + + if (disabledCredential?.state !== 'cooldown') { + throw new Error('Expected cooldown credential') + } + + expect(disabledCredential.cooldownUntil.getTime()).toBe(new Date('2026-01-01T00:00:01.000Z').getTime()) + + jest.useRealTimers() + }) + + it('should reserve gelbooru credentials according to the provider per-key quota', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + const reservations = [] + + for (let i = 0; i < 10; i++) { + reservations.push(await service.reserveAvailableCredential('gelbooru.com')) + } + + const exhaustedReservation = await service.reserveAvailableCredential('gelbooru.com') + + expect(reservations.every((credential) => credential?.user === 'gel-user')).toBe(true) + expect(exhaustedReservation).toBeNull() + expect(service.getMinCooldownSeconds('gelbooru.com')).toBe(1) + + jest.advanceTimersByTime(1_001) + + expect(await service.reserveAvailableCredential('gelbooru.com')).toEqual({ user: 'gel-user', password: 'gel-pass' }) + + jest.useRealTimers() + }) + + it('should expose quota-full credentials as cooldown in status snapshots', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + for (let i = 0; i < 10; i++) { + await service.reserveAvailableCredential('gelbooru.com') + } + + const [snapshot] = service.getCredentialPoolStatus('gelbooru.com') + const credential = snapshot?.credentials.at(0) + + expect(snapshot?.available).toBe(0) + expect(snapshot?.cooldown).toBe(1) + expect(credential).toEqual({ + user: 'gel-user', + state: 'cooldown', + cooldownUntil: '2026-01-01T00:00:01.000Z', + secondsRemaining: 1, + reason: 'quota_exhausted' + }) + + jest.useRealTimers() + }) + + it('should reserve rule34 credentials according to the provider per-key quota', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + for (let i = 0; i < 120; i++) { + expect(await service.reserveAvailableCredential('rule34.xxx')).not.toBeNull() + } + + expect(await service.reserveAvailableCredential('rule34.xxx')).toBeNull() + expect(service.getMinCooldownSeconds('rule34.xxx')).toBe(60) + + jest.advanceTimersByTime(60_001) + + expect(await service.reserveAvailableCredential('rule34.xxx')).not.toBeNull() + + jest.useRealTimers() + }) + + it('should use per-key quota overrides before domain defaults', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + expect(await service.reserveAvailableCredential('gelbooru-override.test')).not.toBeNull() + expect(await service.reserveAvailableCredential('gelbooru-override.test')).not.toBeNull() + expect(await service.reserveAvailableCredential('gelbooru-override.test')).toBeNull() + expect(service.getMinCooldownSeconds('gelbooru-override.test')).toBe(5) + + jest.useRealTimers() + }) + + it('should skip quota-full credentials and reserve another key', async () => { + jest.useFakeTimers() + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) + + await service.reserveAvailableCredential('quota-round-robin.test') + + const selectedCredential = await service.reserveAvailableCredential('quota-round-robin.test') + + expect(selectedCredential?.user).toBe('quota-user-2') + + jest.useRealTimers() + }) + + it('should reactivate credentials after cooldown expiration', async () => { jest.useFakeTimers() jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')) @@ -326,13 +478,17 @@ describe('BooruAuthManagerService', () => { timestamp: new Date() }) - const selectedDuringCooldown = service.getAvailableCredential('https://www.gelbooru.com/index.php?page=dapi') + const selectedDuringCooldown = await service.reserveAvailableCredential( + 'https://www.gelbooru.com/index.php?page=dapi' + ) expect(selectedDuringCooldown).toBeNull() jest.advanceTimersByTime(1_100) - const selectedAfterCooldown = service.getAvailableCredential('https://www.gelbooru.com/index.php?page=dapi') + const selectedAfterCooldown = await service.reserveAvailableCredential( + 'https://www.gelbooru.com/index.php?page=dapi' + ) expect(selectedAfterCooldown).toEqual({ user: 'www-gel-user', password: 'www-gel-pass' }) @@ -426,6 +582,34 @@ describe('BooruAuthManagerService', () => { expect(stats.available).toBe(1) }) + it('should not locally reserve credentials when primary worker reservation IPC times out', async () => { + jest.useFakeTimers() + const originalSend = Reflect.get(process, 'send') as typeof process.send + const sendMock = jest.fn() as jest.MockedFunction> + Reflect.set(process, 'send', sendMock) + + const reservation = (service as unknown as AuthManagerPrivateAccess).reserveAvailableCredentialFromPrimary( + 'gelbooru.com' + ) + + jest.advanceTimersByTime(1_001) + + await expect(reservation).resolves.toBeNull() + expect(sendMock).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'RESERVE_CREDENTIAL' + }) + ) + expect(await service.reserveAvailableCredential('gelbooru.com')).toEqual({ user: 'gel-user', password: 'gel-pass' }) + + if (originalSend === undefined) { + Reflect.deleteProperty(process, 'send') + } else { + Reflect.set(process, 'send', originalSend) + } + jest.useRealTimers() + }) + it('should throw when IPC-serialized Dates are used without reconstruction (proves original bug)', () => { // Without the fix, disableCredentialLocally receives string dates from IPC and crashes const serialized = JSON.parse( diff --git a/src/booru/services/booru-auth-manager.service.ts b/src/booru/services/booru-auth-manager.service.ts index 8d36568..ec3022c 100644 --- a/src/booru/services/booru-auth-manager.service.ts +++ b/src/booru/services/booru-auth-manager.service.ts @@ -1,10 +1,11 @@ -import { Injectable, OnModuleInit } from '@nestjs/common' +import { Inject, Injectable, OnModuleInit } from '@nestjs/common' import { ConfigService } from '@nestjs/config' import cluster from 'cluster' import { BooruAuthConfig, BooruAuthCredential, DisabledCredential, + SerializedDisabledCredential, AuthCredentialStats, DomainCredentialStatus, MaskedCredentialStatus, @@ -12,27 +13,39 @@ import { IpcAuthMessage } from '../interfaces/auth-manager.interface' import { SENSITIVE_AUTH_PARAMS } from '../constants/sensitive-auth-params' +import { + BOORU_AUTH_DOMAIN_ALIASES, + BOORU_AUTH_RATE_LIMIT_DEFAULTS, + RateLimitPolicy +} from '../constants/booru-auth-provider-policies' import { createCredentialKey, parseCredentialKey } from './credential-key.util' +interface ReservationResponse { + credential: BooruAuthCredential | null + retryAfterSeconds?: number +} + @Injectable() 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 private readonly disabledCredentials = new Map() private readonly cooldownCredentials = new Map< string, { disabledAt: number; cooldownUntil: number; reason: string } >() + private readonly quotaReservations = new Map() + private readonly pendingReservationRequests = new Map void>() + private readonly lastReservationUnavailableUntilByDomain = new Map() private readonly selectionCursorByDomain = new Map() private readonly availabilityByDomain = new Map() private authConfig: BooruAuthConfig = {} - private readonly domainAliases: Record = { - 'www.rule34.xxx': 'rule34.xxx', - 'api.rule34.xxx': 'rule34.xxx' - } + private readonly domainRateLimitDefaults: Record = BOORU_AUTH_RATE_LIMIT_DEFAULTS + private readonly domainAliases: Record = BOORU_AUTH_DOMAIN_ALIASES private readonly sensitiveParams = new Set(SENSITIVE_AUTH_PARAMS) - constructor(private readonly configService: ConfigService) {} + constructor(@Inject(ConfigService) private readonly configService: Pick) {} onModuleInit() { this.loadAuthConfig() @@ -58,6 +71,7 @@ export class BooruAuthManagerService implements OnModuleInit { } catch (error) { const message = error instanceof Error ? error.message : String(error) console.error('Failed to parse BOORU_AUTH_CONFIG:', message) + throw error } } @@ -65,51 +79,101 @@ export class BooruAuthManagerService implements OnModuleInit { if (cluster.isWorker && process.send) { process.on('message', (message: IpcAuthMessage) => { if (message.type === 'DISABLE_CREDENTIAL') { - const raw = message.payload as DisabledCredential - // IPC serializes Date objects as ISO strings — reconstruct them before use - const credential: DisabledCredential = - raw.state === 'cooldown' - ? { ...raw, disabledAt: new Date(raw.disabledAt), cooldownUntil: new Date(raw.cooldownUntil) } - : { ...raw, disabledAt: new Date(raw.disabledAt) } - this.disableCredentialLocally(credential) + this.applyDisabledCredential(message.payload) + return + } + + if (message.type === 'RESERVE_CREDENTIAL_RESPONSE') { + const response = message.payload + const resolve = this.pendingReservationRequests.get(response.requestId) + + if (resolve === undefined) { + return + } + + this.pendingReservationRequests.delete(response.requestId) + resolve({ + credential: response.credential, + ...(response.retryAfterSeconds !== undefined ? { retryAfterSeconds: response.retryAfterSeconds } : {}) + }) } }) } } - public getAvailableCredential(domain: string): BooruAuthCredential | null { + public async reserveAvailableCredential(domain: string): Promise { + if (cluster.isWorker && process.send && process.env['NODE_ENV'] === 'production') { + return this.reserveAvailableCredentialFromPrimary(domain) + } + + return this.reserveAvailableCredentialLocally(domain).credential + } + + public reserveAvailableCredentialLocally(domain: string): ReservationResponse { const normalizedDomain = this.normalizeDomain(domain) const credentialsArray = this.authConfig[normalizedDomain] if (!credentialsArray || credentialsArray.length === 0) { - return null + return { credential: null } } this.cleanupExpiredCooldowns(normalizedDomain) + this.cleanupExpiredQuotaReservations(normalizedDomain) - const availableCredentials = credentialsArray.filter( - (credential) => !this.isCredentialUnavailable(normalizedDomain, credential.user, credential.password) - ) + const selectedCredential = this.selectCredentialRoundRobin(normalizedDomain, credentialsArray) - if (availableCredentials.length === 0) { - console.warn( - `🚫 No available credentials for domain: ${normalizedDomain} (${credentialsArray.length} total, all unavailable)` - ) - return null + if (selectedCredential !== null) { + this.recordQuotaReservation(normalizedDomain, selectedCredential) + this.lastReservationUnavailableUntilByDomain.delete(normalizedDomain) + return { credential: selectedCredential } } - const selectedCredential = this.selectCredentialRoundRobin(normalizedDomain, availableCredentials) + const retryAfterSeconds = this.getMinCooldownSeconds(normalizedDomain) - if (selectedCredential === null) { - console.warn(`🚫 No available credentials for domain: ${normalizedDomain} after round-robin selection`) - return null + if (retryAfterSeconds !== undefined) { + this.lastReservationUnavailableUntilByDomain.set(normalizedDomain, Date.now() + retryAfterSeconds * 1_000) } - console.log( - `🔑 Selected credential for ${normalizedDomain}: ${selectedCredential.user} (${availableCredentials.length}/${credentialsArray.length} available)` - ) + return { + credential: null, + ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}) + } + } + + public applyDisabledCredential(credential: DisabledCredential | SerializedDisabledCredential): void { + this.disableCredentialLocally(this.rehydrateDisabledCredential(credential)) + } + + private reserveAvailableCredentialFromPrimary(domain: string): Promise { + return new Promise((resolve) => { + const normalizedDomain = this.normalizeDomain(domain) + const requestId = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}` + const timeout = setTimeout(() => { + this.pendingReservationRequests.delete(requestId) + resolve(null) + }, BooruAuthManagerService.IPC_RESERVATION_TIMEOUT_MS) + + this.pendingReservationRequests.set(requestId, (response) => { + clearTimeout(timeout) + + if (response.retryAfterSeconds !== undefined) { + this.lastReservationUnavailableUntilByDomain.set( + normalizedDomain, + Date.now() + response.retryAfterSeconds * 1_000 + ) + } + + resolve(response.credential) + }) - return selectedCredential + process.send?.({ + type: 'RESERVE_CREDENTIAL', + payload: { + requestId, + domain + } + } satisfies IpcAuthMessage) + }) } public reportAuthFailure(authFailure: AuthFailureEvent): void { @@ -123,7 +187,12 @@ export class BooruAuthManagerService implements OnModuleInit { } const isRateLimit = failureKind === 'rate_limited' - const cooldownSeconds = Math.max(1, authFailure.retryAfterSeconds ?? 60) + 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 baseCredential = { domain: normalizedDomain, @@ -179,11 +248,31 @@ export class BooruAuthManagerService implements OnModuleInit { this.cooldownCredentials.delete(credentialKey) } + private rehydrateDisabledCredential(raw: DisabledCredential | SerializedDisabledCredential): DisabledCredential { + // IPC serializes Date objects as ISO strings — reconstruct them before use. + return raw.state === 'cooldown' + ? { ...raw, disabledAt: new Date(raw.disabledAt), cooldownUntil: new Date(raw.cooldownUntil) } + : { ...raw, disabledAt: new Date(raw.disabledAt) } + } + + private serializeDisabledCredential(credential: DisabledCredential): SerializedDisabledCredential { + return credential.state === 'cooldown' + ? { + ...credential, + disabledAt: credential.disabledAt.toISOString(), + cooldownUntil: credential.cooldownUntil.toISOString() + } + : { + ...credential, + disabledAt: credential.disabledAt.toISOString() + } + } + private broadcastDisabledCredential(credential: DisabledCredential): void { if (cluster.isWorker && process.send) { const message: IpcAuthMessage = { type: 'DISABLE_CREDENTIAL', - payload: credential + payload: this.serializeDisabledCredential(credential) } process.send(message) } @@ -234,7 +323,11 @@ export class BooruAuthManagerService implements OnModuleInit { continue } - if (this.isCooldownActive(fullKey) || this.isCooldownActive(userKey)) { + if ( + this.isCooldownActive(fullKey) || + this.isCooldownActive(userKey) || + this.isQuotaFull(normalizedDomain, credential) + ) { cooldown += 1 } } @@ -291,6 +384,16 @@ export class BooruAuthManagerService implements OnModuleInit { const normalizedDomain = this.normalizeDomain(domain) let minCooldownUntil: number | undefined + const reservationUnavailableUntil = this.lastReservationUnavailableUntilByDomain.get(normalizedDomain) + + if (reservationUnavailableUntil !== undefined) { + if (reservationUnavailableUntil <= Date.now()) { + this.lastReservationUnavailableUntilByDomain.delete(normalizedDomain) + } else { + minCooldownUntil = reservationUnavailableUntil + } + } + for (const [credentialKey, cooldownInfo] of this.cooldownCredentials.entries()) { const { domain: keyDomain } = parseCredentialKey(credentialKey) @@ -310,6 +413,20 @@ export class BooruAuthManagerService implements OnModuleInit { } } + for (const credential of this.authConfig[normalizedDomain] ?? []) { + const quotaRetryAfterSeconds = this.getQuotaRetryAfterSeconds(normalizedDomain, credential) + + if (quotaRetryAfterSeconds === undefined) { + continue + } + + const quotaCooldownUntil = Date.now() + quotaRetryAfterSeconds * 1_000 + + if (minCooldownUntil === undefined || quotaCooldownUntil < minCooldownUntil) { + minCooldownUntil = quotaCooldownUntil + } + } + if (minCooldownUntil === undefined) { return undefined } @@ -356,7 +473,9 @@ export class BooruAuthManagerService implements OnModuleInit { for (const [domain, credentials] of Object.entries(authConfig)) { const normalizedDomain = this.normalizeDomain(domain) - const mergedCredentials = [...(normalizedAuthConfig[normalizedDomain] ?? []), ...credentials] + const validatedCredentials = this.validateAuthConfigCredentials(normalizedDomain, credentials) + + const mergedCredentials = [...(normalizedAuthConfig[normalizedDomain] ?? []), ...validatedCredentials] normalizedAuthConfig[normalizedDomain] = this.dedupeCredentials(mergedCredentials) } @@ -364,6 +483,54 @@ export class BooruAuthManagerService implements OnModuleInit { return normalizedAuthConfig } + private validateAuthConfigCredentials(domain: string, credentials: unknown): BooruAuthCredential[] { + if (!Array.isArray(credentials)) { + throw new Error(`Invalid BOORU_AUTH_CONFIG credentials list for ${domain}`) + } + + const validCredentials: BooruAuthCredential[] = [] + + for (const [index, credential] of credentials.entries()) { + if (!this.isValidAuthCredentialShape(credential)) { + throw new Error(`Invalid BOORU_AUTH_CONFIG credential for ${domain} at index ${index}`) + } + + if (credential.rateLimit !== undefined && !this.isValidRateLimitPolicy(credential.rateLimit)) { + throw new Error(`Invalid BOORU_AUTH_CONFIG rateLimit for ${domain} at index ${index}`) + } + + validCredentials.push(credential) + } + + return validCredentials + } + + private isValidAuthCredentialShape(credential: unknown): credential is BooruAuthCredential { + if (!this.isRecord(credential)) { + return false + } + + const user = credential['user'] + const password = credential['password'] + + return typeof user === 'string' && user.length > 0 && typeof password === 'string' && password.length > 0 + } + + private isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null + } + + private isValidRateLimitPolicy(rateLimit: BooruAuthCredential['rateLimit']): rateLimit is RateLimitPolicy { + if (rateLimit === undefined) { + return false + } + + const requests = Math.floor(rateLimit.requests) + const windowSeconds = Math.floor(rateLimit.windowSeconds) + + return Number.isFinite(requests) && requests > 0 && Number.isFinite(windowSeconds) && windowSeconds > 0 + } + private dedupeCredentials(credentials: BooruAuthCredential[]): BooruAuthCredential[] { const uniqueCredentials = new Map() @@ -556,7 +723,10 @@ export class BooruAuthManagerService implements OnModuleInit { continue } - if (!this.isCredentialUnavailable(domain, candidate.user, candidate.password)) { + if ( + !this.isCredentialUnavailable(domain, candidate.user, candidate.password) && + !this.isQuotaFull(domain, candidate) + ) { this.selectionCursorByDomain.set(domain, (index + 1) % credentials.length) return candidate } @@ -565,6 +735,99 @@ export class BooruAuthManagerService implements OnModuleInit { return null } + private getRateLimitFallbackSeconds(domain: string, user: string, password?: string): number { + const credential = (this.authConfig[domain] ?? []).find( + (candidate) => candidate.user === user && (password === undefined || candidate.password === password) + ) + const policy = credential ? this.getRateLimitPolicy(domain, credential) : this.domainRateLimitDefaults[domain] + + return policy?.windowSeconds ?? 60 + } + + private getRateLimitPolicy(domain: string, credential: BooruAuthCredential): RateLimitPolicy | undefined { + if (credential.rateLimit !== undefined) { + const requests = Math.floor(credential.rateLimit.requests) + const windowSeconds = Math.floor(credential.rateLimit.windowSeconds) + + if (Number.isFinite(requests) && requests > 0 && Number.isFinite(windowSeconds) && windowSeconds > 0) { + return { requests, windowSeconds } + } + } + + return this.domainRateLimitDefaults[this.normalizeDomain(domain)] + } + + private getQuotaReservationKey(domain: string, credential: BooruAuthCredential): string { + return createCredentialKey(this.normalizeDomain(domain), credential.user, credential.password) + } + + private cleanupExpiredQuotaReservations(domain: string): void { + const normalizedDomain = this.normalizeDomain(domain) + + for (const credential of this.authConfig[normalizedDomain] ?? []) { + this.getQuotaRetryAfterSeconds(normalizedDomain, credential) + } + } + + private getQuotaRetryAfterSeconds(domain: string, credential: BooruAuthCredential): number | undefined { + const policy = this.getRateLimitPolicy(domain, credential) + + if (policy === undefined) { + return undefined + } + + const reservationKey = this.getQuotaReservationKey(domain, credential) + const now = Date.now() + const windowMs = policy.windowSeconds * 1_000 + const reservations = this.pruneQuotaReservations(reservationKey, windowMs, now) + + if (reservations.length < policy.requests) { + return undefined + } + + const oldestReservation = reservations[0] + + if (oldestReservation === undefined) { + return undefined + } + + return Math.max(1, Math.ceil((oldestReservation + windowMs - now) / 1_000)) + } + + private isQuotaFull(domain: string, credential: BooruAuthCredential): boolean { + return this.getQuotaRetryAfterSeconds(domain, credential) !== undefined + } + + private recordQuotaReservation(domain: string, credential: BooruAuthCredential): void { + const policy = this.getRateLimitPolicy(domain, credential) + + if (policy === undefined) { + return + } + + const reservationKey = this.getQuotaReservationKey(domain, credential) + const now = Date.now() + const windowMs = policy.windowSeconds * 1_000 + const reservations = this.pruneQuotaReservations(reservationKey, windowMs, now) + + reservations.push(now) + this.quotaReservations.set(reservationKey, reservations) + } + + private pruneQuotaReservations(reservationKey: string, windowMs: number, now: number): number[] { + const reservations = (this.quotaReservations.get(reservationKey) ?? []).filter( + (timestamp) => now - timestamp < windowMs + ) + + if (reservations.length === 0) { + this.quotaReservations.delete(reservationKey) + } else { + this.quotaReservations.set(reservationKey, reservations) + } + + return reservations + } + private getMaskedCredentialStatus(domain: string, credential: BooruAuthCredential): MaskedCredentialStatus { const fullKey = createCredentialKey(domain, credential.user, credential.password) const userKey = createCredentialKey(domain, credential.user) @@ -592,6 +855,18 @@ export class BooruAuthManagerService implements OnModuleInit { } } + const quotaRetryAfterSeconds = this.getQuotaRetryAfterSeconds(domain, credential) + + if (quotaRetryAfterSeconds !== undefined) { + return { + user: credential.user, + state: 'cooldown', + cooldownUntil: new Date(now + quotaRetryAfterSeconds * 1_000).toISOString(), + secondsRemaining: quotaRetryAfterSeconds, + reason: 'quota_exhausted' + } + } + return { user: credential.user, state: 'active' diff --git a/src/cluster.service.spec.ts b/src/cluster.service.spec.ts new file mode 100644 index 0000000..15d42f5 --- /dev/null +++ b/src/cluster.service.spec.ts @@ -0,0 +1,34 @@ +import { getWorkerCount } from './cluster.service' + +describe('getWorkerCount', () => { + const originalNodeEnv = process.env['NODE_ENV'] + const originalWebConcurrency = process.env['WEB_CONCURRENCY'] + + afterEach(() => { + if (originalNodeEnv === undefined) { + delete process.env['NODE_ENV'] + } else { + process.env['NODE_ENV'] = originalNodeEnv + } + + if (originalWebConcurrency === undefined) { + delete process.env['WEB_CONCURRENCY'] + } else { + process.env['WEB_CONCURRENCY'] = originalWebConcurrency + } + }) + + it('uses one worker in development', () => { + process.env['NODE_ENV'] = 'development' + process.env['WEB_CONCURRENCY'] = '8' + + expect(getWorkerCount()).toBe(1) + }) + + it('uses WEB_CONCURRENCY in production when configured', () => { + process.env['NODE_ENV'] = 'production' + process.env['WEB_CONCURRENCY'] = '3' + + expect(getWorkerCount()).toBe(3) + }) +}) diff --git a/src/cluster.service.ts b/src/cluster.service.ts index 5bc9a5f..44acafd 100644 --- a/src/cluster.service.ts +++ b/src/cluster.service.ts @@ -1,14 +1,26 @@ import { Injectable } from '@nestjs/common' import { availableParallelism } from 'os' import cluster from 'cluster' -import { IpcAuthMessage, DisabledCredential } from './booru/interfaces/auth-manager.interface' -import { createCredentialKey } from './booru/services/credential-key.util' +import { IpcAuthMessage } from './booru/interfaces/auth-manager.interface' +import { BooruAuthManagerService } from './booru/services/booru-auth-manager.service' -const numCPUs = process.env['NODE_ENV'] === 'development' ? 1 : availableParallelism() +export function getWorkerCount(): number { + if (process.env['NODE_ENV'] === 'development') { + return 1 + } + + const configuredWorkerCount = Number.parseInt(process.env['WEB_CONCURRENCY'] ?? '', 10) + + if (Number.isFinite(configuredWorkerCount) && configuredWorkerCount > 0) { + return configuredWorkerCount + } + + return availableParallelism() +} @Injectable() export class AppClusterService { - private static readonly disabledCredentials = new Set() + private static primaryAuthManager: BooruAuthManagerService | null = null static clusterize(callback: () => void | Promise): void { if (cluster.isPrimary) { @@ -17,7 +29,7 @@ export class AppClusterService { // Setup IPC message handling for credential management this.setupPrimaryIpcHandling() - for (let i = 0; i < numCPUs; i++) { + for (let i = 0; i < getWorkerCount(); i++) { cluster.fork() } @@ -34,11 +46,9 @@ export class AppClusterService { private static setupPrimaryIpcHandling(): void { cluster.on('message', (worker, message: IpcAuthMessage) => { if (message.type === 'DISABLE_CREDENTIAL') { - const credential = message.payload as DisabledCredential - const credentialKey = createCredentialKey(credential.domain, credential.user, credential.password) + const credential = message.payload - // Store in primary process - this.disabledCredentials.add(credentialKey) + this.getPrimaryAuthManager().applyDisabledCredential(credential) // Broadcast to all other workers Object.values(cluster.workers ?? {}).forEach((w) => { @@ -52,11 +62,35 @@ export class AppClusterService { console.log( `🔄 Broadcasting disabled ${scope} credential for ${credential.domain} to ${Object.keys(cluster.workers ?? {}).length - 1} other workers` ) + return + } + + if (message.type === 'RESERVE_CREDENTIAL') { + const payload = message.payload + const reservation = this.getPrimaryAuthManager().reserveAvailableCredentialLocally(payload.domain) + + worker.send({ + type: 'RESERVE_CREDENTIAL_RESPONSE', + payload: { + requestId: payload.requestId, + credential: reservation.credential, + ...(reservation.retryAfterSeconds !== undefined ? { retryAfterSeconds: reservation.retryAfterSeconds } : {}) + } + } satisfies IpcAuthMessage) } }) } - static getDisabledCredentials(): Set { - return this.disabledCredentials + private static getPrimaryAuthManager(): BooruAuthManagerService { + if (this.primaryAuthManager !== null) { + return this.primaryAuthManager + } + + this.primaryAuthManager = new BooruAuthManagerService({ + get: (key: string) => process.env[key] + }) + this.primaryAuthManager.onModuleInit() + + return this.primaryAuthManager } }