Skip to content

sec: narrow CSRF exemption for approve/cancel POST endpoints (closes #404)#888

Open
cristim wants to merge 1 commit into
feat/multicloud-web-frontendfrom
fix/404-wave21
Open

sec: narrow CSRF exemption for approve/cancel POST endpoints (closes #404)#888
cristim wants to merge 1 commit into
feat/multicloud-web-frontendfrom
fix/404-wave21

Conversation

@cristim
Copy link
Copy Markdown
Member

@cristim cristim commented May 30, 2026

Summary

  • Removes the blanket /api/purchases/approve/ and /api/purchases/cancel/ entries from requiresCSRFValidation's exemption list. These routes are already covered by isPublicEndpoint(), so the middleware never reached CSRF validation on the token-only path anyway -- but the exemption was leaving session-authenticated POSTs unprotected.
  • Adds validateCSRF() calls at the entry of approvePurchaseViaSession and cancelPurchaseViaSession -- the two functions that mutate state under session authentication (issues feat(history): inline Cancel button for pending purchase rows #46/feat(api,history): add Approve button + approve-{any,own} RBAC for in-dashboard purchase approval #286 added these session branches). The token-only (email-link) path never calls these functions and is unaffected.
  • Updates 6 existing tests to supply ValidateCSRFToken expectations on the session-authed branches they exercise, and updates one test whose expected error message changed (CSRF fires before requireSession, so tokenless requests now get 403 instead of 401).

Attack scenario closed

A logged-in user's browser could previously be CSRF-forged into approving or cancelling a purchase if the attacker knew the execution ID. The session branch added in issues #46/#286 bypassed CSRF because the blanket middleware exemption applied unconditionally. This fix closes that gap.

Test plan

  • TestApproveViaSession_RequiresCSRF: session POST without CSRF token -> 403 "CSRF validation failed"
  • TestApproveViaSession_PassesCSRF: session POST with valid CSRF token -> 200 "completed"
  • TestCancelViaSession_RequiresCSRF: session POST without CSRF token -> 403 "CSRF validation failed"
  • TestTokenOnlyApprove_BypassesCSRF: email-link token path never calls ValidateCSRFToken (no mock registered; unexpected call would panic)
  • All 1359 existing internal/api tests pass
  • go build ./... succeeds

Closes #404

@cristim cristim added triaged Item has been triaged priority/p2 Backlog-worthy urgency/this-quarter Within the quarter impact/few Limited audience effort/m Days type/security Security finding labels May 30, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 30, 2026

Warning

Review limit reached

@cristim, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 23 minutes and 45 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d4aa4220-61ad-4a3d-8e3b-0cd38ce79620

📥 Commits

Reviewing files that changed from the base of the PR and between 56a7797 and f8ccbdc.

📒 Files selected for processing (5)
  • internal/api/coverage_gaps_test.go
  • internal/api/handler_purchases.go
  • internal/api/handler_purchases_test.go
  • internal/api/middleware.go
  • internal/api/middleware_test.go
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/404-wave21

Comment @coderabbitai help to get the list of available commands and usage tips.

@cristim
Copy link
Copy Markdown
Member Author

cristim commented May 30, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 30, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

…404)

The blanket "/api/purchases/approve/" and "/api/purchases/cancel/"
entries in requiresCSRFValidation's exempt list were correct for the
original token-only (email-link) flow but became incorrect once the
three-mode dispatch (issues #46/#286) introduced a session-authed branch.
A logged-in user's browser could be CSRF-forged into a POST to these
endpoints because the middleware skipped CSRF validation entirely.

Fix: remove the blanket middleware exemption and instead call
validateCSRF() at the top of approvePurchaseViaSession and
cancelPurchaseViaSession -- the two functions that mutate state under
session authentication. The token-only path (authorizeApprovalAction)
is stateless and never calls these functions, so it remains unaffected.

These routes are already listed in isPublicEndpoint(), so
validateSecurity() short-circuits before requiresCSRFValidation() is
reached on the email-link path; the middleware exemption was therefore
doubly redundant for that path and actively harmful for the session path.

Tests: 4 new boundary tests in middleware_test.go
  - TestApproveViaSession_RequiresCSRF: session POST without CSRF -> 403
  - TestApproveViaSession_PassesCSRF: session POST with CSRF -> 200
  - TestCancelViaSession_RequiresCSRF: session POST without CSRF -> 403
  - TestTokenOnlyApprove_BypassesCSRF: token path never calls CSRF check

Rebased on the group-membership-only authz model (issue #907): admin
sessions no longer short-circuit on Session.Role, so the session-authed
branches resolve approve-*/cancel-* through HasPermissionAPI. Tests that
previously set Session{Role: "admin"} now register grantAdmin() to pass
the dispatcher's authorization gate before reaching the CSRF guard, and
keep their ValidateCSRFToken expectations. No migration needed.
@cristim
Copy link
Copy Markdown
Member Author

cristim commented Jun 3, 2026

Rebased on feat/multicloud-web-frontend. Resolved conflicts in internal/api/handler_purchases_test.go (5 regions) and fixed a post-rebase compile/authz break in internal/api/middleware_test.go:

  • The base picked up the group-membership-only authz model (issue Revamp authorization: group-membership-only (remove roles), require >=1 group per user #907), which removed Session.Role and routes admin through HasPermissionAPI. This PR's tests previously set Session{Role: "admin"}.
  • Reconciled by registering grantAdmin() (mocks HasPermissionAPI true) on the session-authed approve/cancel tests so they pass the dispatcher's authorization gate, while keeping this PR's ValidateCSRFToken expectations intact.
  • Adopted the base's unconditional if session != nil permission-mock block in buildSessionCancelHandler (dropped the stale session.Role != "admin" gate) and kept the CSRF .Maybe() stub.

Production CSRF enforcement (validateCSRF inside approvePurchaseViaSession / cancelPurchaseViaSession) is unchanged. Full internal/api suite green (1399 tests), go vet and go build clean.

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 3, 2026

@cristim Thanks for the detailed rebase summary. The reconciliation approach — using grantAdmin() to mock HasPermissionAPI in place of the removed Session.Role field — looks coherent with the new group-membership authz model from #907, and the production CSRF path remains untouched. Triggering a review of the updated state now.


🧠 Learnings used
Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-05-05T15:44:54.463Z
Learning: In the LeanerCloud/CUDly repository, when a CodeRabbit review flags something as "outside-diff" that was already implemented in an earlier commit of the same PR, it is likely a stale-snapshot artifact where the review diff was generated against a pre-fix view. The inline comment convention `(CR pass on PR #<number> Finding N)` is used by the maintainer (cristim) to mark lines that were changed in direct response to a prior CodeRabbit review pass.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-05-25T21:45:57.471Z
Learning: In this repository (CUDly), `internal/commitmentopts/normalizePayment` is unexported and AWS-spelling-focused (parses "All Upfront"/"ALL_UPFRONT" → canonical AWS tokens). `internal/api/validation.go:purchasePaymentWhitelist` is the purchase-execute boundary. `pkg/common/reservation_name.go:normalizeReservationPayment` produces short-form name segments. These are all distinct concerns from the cross-provider `NormalizePaymentOption` helper in `internal/config/validation.go`.
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@cristim
Copy link
Copy Markdown
Member Author

cristim commented Jun 3, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 3, 2026

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/m Days impact/few Limited audience priority/p2 Backlog-worthy triaged Item has been triaged type/security Security finding urgency/this-quarter Within the quarter

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant