Skip to content

feat(api): authorized origins#221

Merged
alfetopito merged 5 commits into
mainfrom
feat/authorized-origins
Jun 17, 2026
Merged

feat(api): authorized origins#221
alfetopito merged 5 commits into
mainfrom
feat/authorized-origins

Conversation

@alfetopito

@alfetopito alfetopito commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

Harden authorized origins.

Addresses feedback from https://github.com/cowprotocol/infrastructure/pull/5701

Note: in order to preserve current behaviour of accepting subdomains, BFF configs need to be updated from:

"cow.fi, cowswap.vercel.app, cowswap-dev.vercel.app, explorer-dev.vercel.app, swap-dev-5u6.pages.dev, explorer-dev-dxz.pages.dev"

to

".cow.fi, .cowswap.vercel.app, .cowswap-dev.vercel.app, .explorer-dev.vercel.app, .swap-dev-5u6.pages.dev, .explorer-dev-dxz.pages.dev"

Testing

Unit tests

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Strengthened origin authorization by requiring HTTPS, rejecting origins with explicit ports, and tightening hostname matching (exact vs leading-dot subdomain rules).
    • Improved validation of AUTHORIZED_ORIGINS, including startup failures when it’s missing in production or malformed.
  • Tests

    • Added/expanded coverage to verify authorization behavior across unset, single, wildcard, exact, and multi-entry origin configurations.
  • Documentation

    • Updated .env.example guidance for AUTHORIZED_ORIGINS to clarify exact-host vs subdomain (leading-dot) matching.

@alfetopito alfetopito self-assigned this Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

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

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ 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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 01d5405b-672a-4220-853a-2353fb42dbbf

📥 Commits

Reviewing files that changed from the base of the PR and between b9db698 and f5a09f7.

📒 Files selected for processing (1)
  • package.json
📝 Walkthrough

Walkthrough

This PR enforces stricter origin authorization for the BFF with HTTPS-only validation and leading-dot wildcard subdomain matching, documented in environment examples and tested across six configuration scenarios. A separate fix improves test isolation by properly cleaning environment variables in the Coingecko test suite.

Changes

Strict Origin Authorization with Subdomain Matching

Layer / File(s) Summary
Origin authorization implementation
apps/api/src/app/plugins/bffAuth.ts
Refactored AUTHORIZED_ORIGINS parsing into parseAuthorizedOrigins() that normalizes by splitting, trimming, lowercasing, and filtering empty values, throwing in production if undefined or empty. Added isAuthorizedOrigin() to parse origins as URLs, enforce HTTPS-only with no explicit ports, and normalize casing. Added isAuthorizedHostname() supporting leading-dot subdomain suffix matching with length constraint, otherwise exact hostname equality. Replaced direct suffix matching with strict hostname validation in the on-request authorization check.
Configuration examples
.env.example
Updated AUTHORIZED_ORIGINS documentation with clarifying comments on exact-host vs subdomain matching. Expanded example from cow.fi to cow.fi,.cow.fi to demonstrate both bare and leading-dot subdomain entry forms.
Authorization test coverage
apps/api/src/app/plugins/bffAuth.spec.ts
Added comprehensive Jest test suite with buildApp helper for isolated module reloading, request injection helpers for protected and public routes, and per-test cleanup. Covers startup validation (throws on malformed or missing AUTHORIZED_ORIGINS in production) and six configuration scenarios: unset origins (allow any), bare hostnames (exact + suffix-squatting and scheme validation), leading-dot entries (root and subdomains), exact subdomains (blocking parent/sub-subdomains), leading-dot patterns (subdomains only), and multiple entries (per-entry matching with cross-entry suffix-squatting prevention).

Test Environment Isolation

Layer / File(s) Summary
Environment variable cleanup in test
libs/repositories/src/datasources/coingecko.test.ts
Fixed the getCoingeckoProClient error-path test to preserve and restore the original process.env.COINGECKO_API_KEY using a try/finally block, preventing environment leakage across test runs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit hops through origins secure,
HTTPS paths and subdomains pure,
Leading-dot patterns match just right,
Tests confirm each auth-check bright! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(api): authorized origins' accurately reflects the main change: implementing enhanced authorized origins handling for the API with validation, production safeguards, and support for both exact-host and subdomain-matching patterns.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/authorized-origins

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/api/src/app/plugins/bffAuth.ts`:
- Around line 12-15: The parsing currently trims and filters AUTHORIZED_ORIGINS
into an array (the domains variable result) but doesn't fail when the env is
present yet yields no valid entries, which silently disables origin protection;
change the startup logic that produces the parsed origins array
(authorizedOrigins) to detect when process.env.AUTHORIZED_ORIGINS is set but
parsed array length === 0 and then fail-closed (throw an Error or exit) with a
clear message about malformed AUTHORIZED_ORIGINS instead of returning an empty
array, and also update the middleware conditional that currently skips auth when
authorizedOrigins is empty to assume a malformed configuration rather than
allowing requests (i.e., require successful parse or stop startup).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e6df991b-a933-4cf6-970d-32d229ba3230

📥 Commits

Reviewing files that changed from the base of the PR and between a160920 and c0678c7.

📒 Files selected for processing (4)
  • .env.example
  • apps/api/src/app/plugins/bffAuth.spec.ts
  • apps/api/src/app/plugins/bffAuth.ts
  • libs/repositories/src/datasources/coingecko.test.ts

Comment thread apps/api/src/app/plugins/bffAuth.ts Outdated
@alfetopito alfetopito requested review from a team, limitofzero and shoom3301 June 9, 2026 15:46
Comment thread apps/api/src/app/plugins/bffAuth.ts
@alfetopito alfetopito merged commit 2055852 into main Jun 17, 2026
9 checks passed
@alfetopito alfetopito deleted the feat/authorized-origins branch June 17, 2026 15:26
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.

2 participants