This commit is contained in:
anatawa12 2024-09-17 21:01:35 +09:00 committed by GitHub
commit 73640f3515
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 65 additions and 81 deletions

View File

@ -149,6 +149,7 @@
- Fix: アンテナ・クリップ・リスト・ウェブフックがロールポリシーの上限より一つ多く作れてしまうのを修正 (#14036) - Fix: アンテナ・クリップ・リスト・ウェブフックがロールポリシーの上限より一つ多く作れてしまうのを修正 (#14036)
- Fix: notRespondingSinceが実装される前に不通になったインスタンスが自動的に配信停止にならない (#14059) - Fix: notRespondingSinceが実装される前に不通になったインスタンスが自動的に配信停止にならない (#14059)
- Fix: FTT有効時、タイムライン用エンドポイントで`sinceId`にキャッシュ内最古のものより古いものを指定した場合に正しく結果が返ってこない問題を修正 - Fix: FTT有効時、タイムライン用エンドポイントで`sinceId`にキャッシュ内最古のものより古いものを指定した場合に正しく結果が返ってこない問題を修正
- Fix: レートリミットのfactorが二回適用されて二乗の効果がある問題を修正 (#13997)
- Fix: 自分以外のクリップ内のノート個数が見えることがあるのを修正 - Fix: 自分以外のクリップ内のノート個数が見えることがあるのを修正
- Fix: 空文字列のリアクションはフォールバックされるように - Fix: 空文字列のリアクションはフォールバックされるように
- Fix: リノートにリアクションできないように - Fix: リノートにリアクションできないように

View File

@ -326,19 +326,15 @@ export class ApiCallService implements OnApplicationShutdown {
if (factor > 0) { if (factor > 0) {
// Rate limit // Rate limit
await this.rateLimiterService.limit(limit as IEndpointMeta['limit'] & { key: NonNullable<string> }, limitActor, factor).catch(err => { const rateLimit = await this.rateLimiterService.limit(limit as IEndpointMeta['limit'] & { key: NonNullable<string> }, limitActor, factor);
if ('info' in err) { if (rateLimit != null) {
// errはLimiter.LimiterInfoであることが期待される
throw new ApiError({ throw new ApiError({
message: 'Rate limit exceeded. Please try again later.', message: 'Rate limit exceeded. Please try again later.',
code: 'RATE_LIMIT_EXCEEDED', code: 'RATE_LIMIT_EXCEEDED',
id: 'd5826d14-3982-4d2e-8011-b9e9f02499ef', id: 'd5826d14-3982-4d2e-8011-b9e9f02499ef',
httpStatusCode: 429, httpStatusCode: 429,
}, err.info); }, rateLimit.info);
} else {
throw new TypeError('information must be a rate-limiter information.');
} }
});
} }
} }

View File

@ -12,6 +12,14 @@ import { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js'; import { bindThis } from '@/decorators.js';
import type { IEndpointMeta } from './endpoints.js'; import type { IEndpointMeta } from './endpoints.js';
type RateLimitInfo = {
code: 'BRIEF_REQUEST_INTERVAL',
info: Limiter.LimiterInfo,
} | {
code: 'RATE_LIMIT_EXCEEDED',
info: Limiter.LimiterInfo,
}
@Injectable() @Injectable()
export class RateLimiterService { export class RateLimiterService {
private logger: Logger; private logger: Logger;
@ -31,77 +39,57 @@ export class RateLimiterService {
} }
@bindThis @bindThis
public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1) { private checkLimiter(options: Limiter.LimiterOption): Promise<Limiter.LimiterInfo> {
{ return new Promise<Limiter.LimiterInfo>((resolve, reject) => {
new Limiter(options).get((err, info) => {
if (err) {
return reject(err);
}
resolve(info);
});
});
}
@bindThis
public async limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1): Promise<RateLimitInfo | null> {
if (this.disabled) { if (this.disabled) {
return Promise.resolve(); return null;
} }
// Short-term limit // Short-term limit
const min = new Promise<void>((ok, reject) => { if (limitation.minInterval != null) {
const minIntervalLimiter = new Limiter({ const info = await this.checkLimiter({
id: `${actor}:${limitation.key}:min`, id: `${actor}:${limitation.key}:min`,
duration: limitation.minInterval! * factor, duration: limitation.minInterval * factor,
max: 1, max: 1,
db: this.redisClient, db: this.redisClient,
}); });
minIntervalLimiter.get((err, info) => {
if (err) {
return reject({ code: 'ERR', info });
}
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`); this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
if (info.remaining === 0) { if (info.remaining === 0) {
return reject({ code: 'BRIEF_REQUEST_INTERVAL', info }); // eslint-disable-next-line no-throw-literal
} else { return { code: 'BRIEF_REQUEST_INTERVAL', info };
if (hasLongTermLimit) {
return max.then(ok, reject);
} else {
return ok();
} }
} }
});
});
// Long term limit // Long term limit
const max = new Promise<void>((ok, reject) => { if (limitation.duration != null && limitation.max != null) {
const limiter = new Limiter({ const info = await this.checkLimiter({
id: `${actor}:${limitation.key}`, id: `${actor}:${limitation.key}`,
duration: limitation.duration! * factor, duration: limitation.duration,
max: limitation.max! / factor, max: limitation.max / factor,
db: this.redisClient, db: this.redisClient,
}); });
limiter.get((err, info) => {
if (err) {
return reject({ code: 'ERR', info });
}
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`); this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
if (info.remaining === 0) { if (info.remaining === 0) {
return reject({ code: 'RATE_LIMIT_EXCEEDED', info }); // eslint-disable-next-line no-throw-literal
} else { return { code: 'RATE_LIMIT_EXCEEDED', info };
return ok(); }
} }
});
});
const hasShortTermLimit = typeof limitation.minInterval === 'number'; return null;
const hasLongTermLimit =
typeof limitation.duration === 'number' &&
typeof limitation.max === 'number';
if (hasShortTermLimit) {
return min;
} else if (hasLongTermLimit) {
return max;
} else {
return Promise.resolve();
}
}
} }
} }

View File

@ -73,10 +73,9 @@ export class SigninApiService {
return { error }; return { error };
} }
try {
// not more than 1 attempt per second and not more than 10 attempts per hour // not more than 1 attempt per second and not more than 10 attempts per hour
await this.rateLimiterService.limit({ key: 'signin', duration: 60 * 60 * 1000, max: 10, minInterval: 1000 }, getIpHash(request.ip)); const rateLimit = await this.rateLimiterService.limit({ key: 'signin', duration: 60 * 60 * 1000, max: 10, minInterval: 1000 }, getIpHash(request.ip));
} catch (err) { if (rateLimit != null) {
reply.code(429); reply.code(429);
return { return {
error: { error: {