Rate limit merge request diff reads
What does this MR do and why?
Adds an application rate limit, merge_requests_read_diffs, to the four REST API endpoints that read
whole merge request diffs:
GET /api/v4/projects/:id/merge_requests/:merge_request_iid/changesGET /api/v4/projects/:id/merge_requests/:merge_request_iid/diffsGET /api/v4/projects/:id/merge_requests/:merge_request_iid/raw_diffsGET /api/v4/projects/:id/merge_requests/:merge_request_iid/versions/:version_id
The issue covers the first three. The version endpoint also returns every diff in a version, so it shares the limit; otherwise a throttled caller could read the same diffs through it instead.
These endpoints had no application rate limit, and a single caller can read diffs heavily enough to
degrade the instance. The limit is shared by the three endpoints, and each page of diffs counts as one
request. It applies per user, or per IP address for unauthenticated requests: all three endpoints can be
called without signing in on public projects, so a key on the user alone would not count anonymous
callers. The default is 300 requests per minute, and admins can change it with
merge_requests_read_diffs_limit in the application settings API. There is no admin UI field yet,
matching merge_requests_rebase_limit. It can be added once the default is tuned.
This MR covers only the REST API endpoints. The web diff routes, including the .diff and .patch URLs,
are not changed here.
The limit starts in log mode: while merge_requests_read_diffs_rate_limit_enforce (gitlab_com_derisk,
default off) is disabled, requests over the limit are logged but not blocked. That lets us tune the default
from production data before it blocks anyone. Anonymous callers are checked against the flag with the
:instance actor, so they are blocked as soon as the flag is fully enabled.
References
Screenshots or screen recordings
Not applicable: API only, no UI change.
How to set up and validate locally
- In the Rails console, lower the limit and enable enforcement:
ApplicationSetting.current.update!(merge_requests_read_diffs_limit: 2) Feature.enable(:merge_requests_read_diffs_rate_limit_enforce) - Call the endpoint three times with a personal access token:
The third request returns
for i in 1 2 3; do curl -s -o /dev/null -w "%{http_code}\n" --header "PRIVATE-TOKEN: <token>" \ "http://gdk.test:8080/api/v4/projects/<id>/merge_requests/<iid>/diffs" done429. - Disable the flag and repeat. All requests return
200. The third one is recorded inlog/api_json.logwithrate_limit_stateending inlimit_merge_request_diff_reads_by_user_or_ip_log:log. With the flag enabled, the throttled request is also logged tolog/auth_json.logasApplication_Rate_Limiter_Request.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.