Skip to content

fix: [OCISDEV-825] Rate-limit the exportPersonalData endpoint - #12519

Merged
2403905 merged 2 commits into
masterfrom
fix/OCISDEV-825
Jul 8, 2026
Merged

2403905 merged 2 commits into
masterfrom
fix/OCISDEV-825

Conversation

@2403905

@2403905 2403905 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Bugfix: Rate-limit the exportPersonalData endpoint

We've added a rate limit to the exportPersonalData
endpoint to mitigate an authenticated application-level denial-of-service.
Rate-limit per endpoint path carries the userID, so effectively per user.
The endpoint is now limited to 5 requests per minute.

@2403905
2403905 requested a review from a team as a code owner July 7, 2026 15:24
@kw-security

kw-security commented Jul 7, 2026 •

Copy link
Copy Markdown

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues
✅ Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@dj4oC dj4oC left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds a 5-req/min rate limit to POST /v1.0/users/{userID}/exportPersonalData in the Graph service to mitigate an authenticated app-level DoS (#12516), via a newly-vendored go-chi/httprate, keyed by httprate.KeyByEndpoint (the raw r.URL.Path).

Findings

Security (blocking). Confirmed by reading services/graph/pkg/service/v0/service.go and personaldata.go on the PR branch: the rate-limit middleware is attached via r.With(...) and therefore runs before ExportPersonalData's own "uid mismatch" check (personaldata.go:47-52). Since the limiter's key is r.URL.Path — which contains the target {userID} segment, not the caller's authenticated identity — any authenticated user can grief a specific victim by POSTing /v1.0/users/{victimID}/exportPersonalData up to 5×/min. Each request gets rejected with 400 ("personal data export for other users are not permitted"), but it still consumes the victim's rate-limit budget, since that check only happens in the handler, after the limiter. After 5 such attacker requests, the real victim gets 429 on their own legitimate export. GET /v1.0/users (service.go:303) carries no requireAdmin gate, so target userIDs are discoverable by any authenticated user — this is practical, not theoretical. Recommend keying the limiter off the authenticated caller's ID (already available via context from upstream auth middleware) instead of the URL path, so the mitigation can't be turned into a cross-user denial-of-service tool.

Also raised independently by the security/stability passes: the counter is in-memory/per-process (vendor/github.com/go-chi/httprate/local_counter.go), so in a horizontally-scaled Graph deployment the effective limit becomes 5 × replica count, not a hard global 5/min. Not blocking by itself, but worth a one-line callout in the changelog so operators don't assume a global guarantee.

Stability. Verified the /me alias (service.go:292-301) does not register exportPersonalData, so there's no accidental bucket-sharing via that route. No other regressions found.

Performance. No blocking issues — call volume is inherently low for a data-export endpoint; the added mutex/map overhead and the one allocation from JoinKeys's internal strings.Builder (invoked even with a single key function) are both negligible at this scale.

Test coverage. The new unit test (personaldata_ratelimit_test.go) verifies the middleware composition in isolation via a hand-built flat router, not NewService()'s real nested route tree, and it only ever calls the endpoint as the matching user — it never simulates the cross-user griefing case above, so it would not have caught it. Recommend adding a test where user A's requests target user B's path, plus (per policy) an integration/e2e test exercising the real NewService() mux for the externally-observable 429/Retry-After behavior.

Deployment topology check

Concern — the in-memory-only counter weakens the guarantee under k8s multi-pod/multi-replica scaling of the Graph service (see above). Not blocking on its own, but should be called out in docs/changelog.

Verdict

Changes requested — the rate-limit key should be derived from the authenticated caller, not the target-URL path, to close the cross-user griefing vector before this merges.

🤖 Automated review by Claude Code (security · stability · performance · coverage)


Generated by Claude Code

@2403905

2403905 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Adds a 5-req/min rate limit to POST /v1.0/users/{userID}/exportPersonalData in the Graph service to mitigate an authenticated app-level DoS (#12516), via a newly-vendored go-chi/httprate, keyed by httprate.KeyByEndpoint (the raw r.URL.Path).

Findings

Security (blocking). Confirmed by reading services/graph/pkg/service/v0/service.go and personaldata.go on the PR branch: the rate-limit middleware is attached via r.With(...) and therefore runs before ExportPersonalData's own "uid mismatch" check (personaldata.go:47-52). Since the limiter's key is r.URL.Path — which contains the target {userID} segment, not the caller's authenticated identity — any authenticated user can grief a specific victim by POSTing /v1.0/users/{victimID}/exportPersonalData up to 5×/min. Each request gets rejected with 400 ("personal data export for other users are not permitted"), but it still consumes the victim's rate-limit budget, since that check only happens in the handler, after the limiter. After 5 such attacker requests, the real victim gets 429 on their own legitimate export. GET /v1.0/users (service.go:303) carries no requireAdmin gate, so target userIDs are discoverable by any authenticated user — this is practical, not theoretical. Recommend keying the limiter off the authenticated caller's ID (already available via context from upstream auth middleware) instead of the URL path, so the mitigation can't be turned into a cross-user denial-of-service tool.

Also raised independently by the security/stability passes: the counter is in-memory/per-process (vendor/github.com/go-chi/httprate/local_counter.go), so in a horizontally-scaled Graph deployment the effective limit becomes 5 × replica count, not a hard global 5/min. Not blocking by itself, but worth a one-line callout in the changelog so operators don't assume a global guarantee.

Stability. Verified the /me alias (service.go:292-301) does not register exportPersonalData, so there's no accidental bucket-sharing via that route. No other regressions found.

Performance. No blocking issues — call volume is inherently low for a data-export endpoint; the added mutex/map overhead and the one allocation from JoinKeys's internal strings.Builder (invoked even with a single key function) are both negligible at this scale.

Test coverage. The new unit test (personaldata_ratelimit_test.go) verifies the middleware composition in isolation via a hand-built flat router, not NewService()'s real nested route tree, and it only ever calls the endpoint as the matching user — it never simulates the cross-user griefing case above, so it would not have caught it. Recommend adding a test where user A's requests target user B's path, plus (per policy) an integration/e2e test exercising the real NewService() mux for the externally-observable 429/Retry-After behavior.

Deployment topology check

Concern — the in-memory-only counter weakens the guarantee under k8s multi-pod/multi-replica scaling of the Graph service (see above). Not blocking on its own, but should be called out in docs/changelog.

Verdict

Changes requested — the rate-limit key should be derived from the authenticated caller, not the target-URL path, to close the cross-user griefing vector before this merges.

🤖 Automated review by Claude Code (security · stability · performance · coverage)

Generated by Claude Code

@dj4oC

Regarding the feedback on the in-memory vs. distributed (shared cache) rate limiter, I would like to clarify why a distributed implementation is not practical or necessary for this specific endpoint:

  • Infrequent Endpoint Usage & Low Attack impact the exportPersonalData endpoint is inherently used very rarely by legitimate users.Even if an attacker discovers valid user IDs and targeted a specific user/group, the probability of the actual victim attempting a legitimate export at that exact same moment is extremely low. The impact of someone temporarily blocking another user's exports is too low to justify a complex infrastructure overhead.
  • Application-Level Limitations for DoS Protection a shared cache rate limiter does not solve the underlying application-level DoS/resource exhaustion issue. If an attacker floods the system (even with non-existent IDs that immediately result in validation failures), the CPU and network overhead required to process the incoming HTTP requests and hit the shared cache (e.g., NATS KV) is extremely high. True volumetric DoS protection must be handled upstream (e.g., at the API Gateway or WAF level), not within the application logic.
  • Negligible Multi-Replica Leakage (Diminishing Returns)Introducing a distributed rate limiter adds significant architectural complexity for minimal security gain.In our load tests (1 node, 10,000 requests, 100 parallel workers), the in-memory limiter successfully blocked almost everything: only 9 requests returned 202, while 9,991 requests were correctly choked with 429. Even scaling the Graph service horizontally to 5 replicas would only yield roughly 10 * 5 = 50 allowed requests per minute globally. This volume is completely negligible and poses minimal risk of a critical system overload.
=== POST https://localhost:9200/graph/v1.0/users/058bff95-6708-4fe5-91e4-9ea3d377588b/exportPersonalData
=== 10000 requests, 100 parallel worker(s) ===
--- status code distribution ---
   9 - 202
9991 - 429

=== total 60.277s for 10000 req  ->  165.90 req/s ===

@2403905
2403905 requested a review from dj4oC July 7, 2026 19:44
@dj4oC

dj4oC commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Thanks for the detailed load-test data — the argument about in-memory vs. distributed rate-limiting (concern #2 in the review) is well-reasoned and I agree the operational complexity isn't worth it for this endpoint. That concern is withdrawn.

The blocking concern (concern #1) is a separate issue that still needs addressing before merge:

The rate-limit key is currently the target URL path — specifically the victim's {userID} segment — not the authenticated caller's identity.

Any authenticated user can send POST /v1.0/users/{victimID}/exportPersonalData five times, consume the victim's rate-limit budget (each request returns 400 before the check reaches the caller's auth, but the limiter fires on middleware, before personaldata.go:47-52), and then the real victim gets 429 on their own legitimate request. Your load test demonstrates the limiter working correctly for the same-caller scenario — it doesn't cover the cross-user case.

The fix is small: replace httprate.KeyByEndpoint with a key function that extracts the authenticated caller's identity from the request context (it's already available via the upstream auth middleware). Something like:

// Instead of:
httprate.LimitByIP(5, time.Minute)  // or KeyByEndpoint

// Key by authenticated caller, not target URL:
httprate.NewRateLimiter(5, time.Minute, &httprate.Options{
    KeyFuncs: []httprate.KeyFunc{func(r *http.Request) (string, error) {
        // extract from context — auth middleware populates this
        if uid := middleware.UserIDFromContext(r.Context()); uid != "" {
            return uid, nil
        }
        return httprate.KeyByIP(r)  // fallback
    }},
})

Concern #2 (in-memory / per-replica): accepted, no change needed.
Concern #1 (cross-user griefing via URL-path key): still blocking — please change the limiter key to the authenticated caller's identity.

🤖 Automated review by Claude Code (security · stability · performance · coverage)

@2403905

2403905 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed load-test data — the argument about in-memory vs. distributed rate-limiting (concern #2 in the review) is well-reasoned and I agree the operational complexity isn't worth it for this endpoint. That concern is withdrawn.

The blocking concern (concern #1) is a separate issue that still needs addressing before merge:

The rate-limit key is currently the target URL path — specifically the victim's {userID} segment — not the authenticated caller's identity.

Any authenticated user can send POST /v1.0/users/{victimID}/exportPersonalData five times, consume the victim's rate-limit budget (each request returns 400 before the check reaches the caller's auth, but the limiter fires on middleware, before personaldata.go:47-52), and then the real victim gets 429 on their own legitimate request. Your load test demonstrates the limiter working correctly for the same-caller scenario — it doesn't cover the cross-user case.

The fix is small: replace httprate.KeyByEndpoint with a key function that extracts the authenticated caller's identity from the request context (it's already available via the upstream auth middleware). Something like:

// Instead of:
httprate.LimitByIP(5, time.Minute)  // or KeyByEndpoint

// Key by authenticated caller, not target URL:
httprate.NewRateLimiter(5, time.Minute, &httprate.Options{
    KeyFuncs: []httprate.KeyFunc{func(r *http.Request) (string, error) {
        // extract from context — auth middleware populates this
        if uid := middleware.UserIDFromContext(r.Context()); uid != "" {
            return uid, nil
        }
        return httprate.KeyByIP(r)  // fallback
    }},
})

Concern #2 (in-memory / per-replica): accepted, no change needed. Concern #1 (cross-user griefing via URL-path key): still blocking — please change the limiter key to the authenticated caller's identity.

🤖 Automated review by Claude Code (security · stability · performance · coverage)

Checking user ID is not a rate limiter's responsibility, it is a validation responsibility. We shouldn't mix it.

dj4oC commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Checking user ID is not a rate limiter's responsibility, it is a validation responsibility. We shouldn't mix it.

I'd separate two different things that are getting conflated here:

  1. Validation — does the caller's ID match the target {userID}? That check already exists in personaldata.go:47-52 and this review has never asked to touch it. Agreed that's not the limiter's job.
  2. Key selection — whose budget does a given request draw down? That's not validation, it's the rate limiter's own core responsibility — a limiter without a well-chosen key is just a global counter with extra steps. Keying by the authenticated caller instead of the request-path/target is the standard shape of "per-user rate limiting" everywhere it's implemented (this isn't a bespoke ask specific to this endpoint).

Concretely: with the current httprate.KeyByEndpoint key, the bucket is shared by whoever gets targeted in the URL, not by whoever is making the request. That's what lets any authenticated caller spend a victim's 5 req/min by POSTing to the victim's path — no validation logic needs to move for that to happen, because the limiter fires before validation ever runs. Swapping the key function to the caller's identity (from context, already populated by upstream auth middleware) fixes the griefing vector without adding a single line of authorization logic into the rate-limiter package itself — it stays a pure key-selection change, same middleware, same handler.

If the team's call is to accept this as a known, low-severity tradeoff rather than change the key, that's a legitimate maintainer risk-acceptance decision — but it should be an explicit sign-off from a human maintainer rather than this thread converging on "no change" by attrition. Leaving this PR's review at Changes requested pending that decision.

🤖 Automated review by Claude Code (security · stability · performance · coverage)


Generated by Claude Code

@2403905
2403905 force-pushed the fix/OCISDEV-825 branch 2 times, most recently from af1f5d1 to 0c15d8c Compare July 8, 2026 09:07
@2403905 2403905 changed the title fix: Rate-limit the exportPersonalData endpoint fix: [OCISDEV-825] Rate-limit the exportPersonalData endpoint Jul 8, 2026
@2403905
2403905 force-pushed the fix/OCISDEV-825 branch from 0c15d8c to 7dc5ba8 Compare July 8, 2026 12:07

dj4oC commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Update after re-checking the current head commit (7dc5ba8):

Concern #1 (cross-user griefing via URL-path key) — resolved. The latest push extracted the "uid mismatch" check out of the handler into a new graphmw.RequireSelfUserID middleware and chains it before the rate limiter: r.With(graphmw.RequireSelfUserID(options.Logger)).With(middlewarepkg.LimiterPerEndpoint(...)). Since chi applies .With() middlewares in registration order, a request targeting another user's {userID} is now rejected by RequireSelfUserID before it ever reaches the limiter, so it can no longer consume the victim's budget. This achieves the same security property as my original suggestion (key by caller identity), via a different mechanism (gate first, then key-by-path) — both are valid, and @mklos-kw's approval on this commit reflects that sign-off.

Residual, non-blocking: personaldata_ratelimit_test.go still builds its own isolated router (buildRateLimitedRouter) that only wires up httprate.LimitBy(..., KeyByEndpoint) — it doesn't include RequireSelfUserID in the chain, so it wouldn't catch a future regression where someone reorders the middlewares or drops the self-check. Worth a follow-up test that exercises the actual composed route (or at least asserts ordering), but not blocking this PR.

Withdrawing "changes requested" — no remaining objection to merging as-is.

🤖 Automated review by Claude Code (security · stability · performance · coverage)


Generated by Claude Code

@dj4oC dj4oC left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at current head (7dc5ba8). The blocking concern from my earlier review (rate-limit key derived from attacker-controlled URL path, enabling cross-user budget griefing) is resolved: RequireSelfUserID middleware now runs before the rate limiter and rejects cross-user requests before they can consume the limiter's budget. See inline comment for the residual non-blocking test-coverage note (the unit test doesn't exercise the composed middleware chain).

Verdict

Approved — withdrawing the earlier changes-requested.

🤖 Automated review by Claude Code (security · stability · performance · coverage)


Generated by Claude Code

@2403905
2403905 merged commit c66464c into master Jul 8, 2026
70 checks passed
@2403905
2403905 deleted the fix/OCISDEV-825 branch July 8, 2026 12:57
mklos-kw pushed a commit that referenced this pull request Nov 12, 2026
* fix: Rate-limit the exportPersonalData endpoint

* fix: the RequreSelfUserID validation middleware added

Signed-off-by: Michal Klos <[email protected]>
mmattel pushed a commit that referenced this pull request Nov 12, 2026
* fix: [OCISDEV-810] fix the space role and custom role checks (#12540)

* fix: [OCISDEV-810] fix the space role and custom role checks

* test: [OCISDEV-810] expect 400 when updating a share to a disabled role

The update (PATCH) permission handlers now enforce the admin role
allowlist, consistent with invite. Updating a share to a disabled role
(Secure Viewer, Denied, Space Editor Without Versions) therefore returns
400 instead of the previous silent 200. Update the @issue-10768 scenarios
to assert the new, correct behavior.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Signed-off-by: Michal Klos <[email protected]>

* WIP: bump reva pin to backport/8.0/security-fixes-consolidated tip (OCISDEV-810)

Pins to reva@72978fc55553 (prerequisite #631 + OCISDEV-810 #653 on reva's
stable-8.0 consolidated backport branch) purely to exercise ocis CI against
the fix before reva's PR merges. Re-pin to the merged commit once reva#806
lands.

Signed-off-by: Michal Klos <[email protected]>

* FIX[OCISDEV-809]: encrypt viewOnlyToken (#12558)

fix(OCIDDEV-809): encrypt viewOnlyToken in the WOPI token

Signed-off-by: Michal Klos <[email protected]>

* feat: [OCISDEV-720] fix public link (#12332)

Signed-off-by: Michal Klos <[email protected]>

* WIP: bump reva pin to backport/8.0/security-fixes-consolidated tip (OCISDEV-720)

Pins to reva@4f9a7ac25cfc (OCISDEV-971 + OCISDEV-720 on reva's stable-8.0
consolidated backport branch) purely to exercise ocis CI against the fix
before reva's PR merges. Re-pin to the merged commit once reva#806 lands.

Signed-off-by: Michal Klos <[email protected]>

* fix: [OCISDEV-1404] harden public link brute force protection (#12944)

The proxy public share authenticator set the brute force protection skip
marker on every authentication, including requests where the proxy is the
only authenticator. Failed password attempts on those requests were never
counted, so the rate limit for password protected public links was not
enforced.

The skip marker is now only set for requests that are re-authenticated
downstream, so failed attempts are reliably counted and the throttle is
applied consistently.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Michal Klos <[email protected]>

* fix: [OCISDEV-750] Prevent error information disclosure (#12398)

Signed-off-by: Michal Klos <[email protected]>

* fix: [OCISDEV-825] Rate-limit the exportPersonalData endpoint (#12519)

* fix: Rate-limit the exportPersonalData endpoint

* fix: the RequreSelfUserID validation middleware added

Signed-off-by: Michal Klos <[email protected]>

* fix: private user information available only for admin and the user (#12327)

* fix: private user information available only for admin and the user

* fix: adjust unit tests

Signed-off-by: Michal Klos <[email protected]>

---------

Signed-off-by: Michal Klos <[email protected]>
Co-authored-by: Roman Perekhod <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Firas Frikha <[email protected]>
Co-authored-by: Roman Perekhod <[email protected]>
Co-authored-by: Awab Abdoun <[email protected]>
Co-authored-by: Juan Pablo Villafañez <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants