Skip to content

Add validation for API key IP and Referrer restrictions in DevPortal#1393

Open
Gayuth-W wants to merge 9 commits into
wso2:mainfrom
Gayuth-W:fix/validate-ip
Open

Add validation for API key IP and Referrer restrictions in DevPortal#1393
Gayuth-W wants to merge 9 commits into
wso2:mainfrom
Gayuth-W:fix/validate-ip

Conversation

@Gayuth-W

Copy link
Copy Markdown

Purpose

The DevPortal API key generation dialogs accept any string as a Security Restriction value - a key generates successfully with an IP or Referrer restriction that can never match, silently producing an unusable or falsely-restricted key.

Approach

Added isValidPermittedIPList / isValidPermittedRefererList to the existing Shared/AppsAndKeys/constraintValidator.js and wired them into both key generation dialogs (ApiKeyGenerate/ApiKeyListing and LegacyApiKeys) with an inline field error alongside the existing toast. Rules mirror what the gateway accepts (ApiKeyAuthenticatorUtils#validateAPIKeyRestrictions):

  • IP - comma separated IPv4/IPv6 addresses or CIDR ranges, same patterns as the Admin Portal blacklist form
image
  • Referrer - comma-separated URL/host/wildcard patterns; non-empty, no whitespace, must contain one of . : / *
image

Covered by unit tests (npx jest: 74/74 passing); verified manually on a local APIM 4.7.0 instance.

Fixes wso2/api-manager#5093

Gayuth-W added 2 commits July 16, 2026 16:30
- Add isValidPermittedIPList and isValidPermittedRefererList for validating DevPortal API key Security Restriction inputs, with rules derived from what the gateway accepts (ApiKeyAuthenticatorUtils#validateAPIKeyRestrictions):
- IP: comma-separated IPv4/IPv6 addresses or CIDR ranges, using the same address patterns as the Admin Portal blacklist form
- Referrer: comma-separated URL/host/wildcard patterns; the gateway matches entries literally with '*' wildcards, so each entry must be non-empty, whitespace-free, and contain one of '.', ':', '/', '*'
- Reject invalid Security Restriction values before generating an API key, in both the per-API key dialog (ApiKeyGenerate/ApiKeyListing) and the legacy application key dialog (LegacyApiKeys). Previously any string was accepted and a key was generated with a restriction that could never match.
- Show an inline field error alongside the existing alert toast, clear it when the value or restriction type changes, and update the field placeholders to document the accepted formats.
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Gayuth-W, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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

How do review limits work?

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

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, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f4f81785-96a1-4f5c-8d04-a03add0372a1

📥 Commits

Reviewing files that changed from the base of the PR and between 0a6c296 and e0a1561.

📒 Files selected for processing (1)
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx
📝 Walkthrough

Walkthrough

Added shared validation for IP/CIDR and referrer restrictions during standard and legacy API key generation. Invalid values now stop generation, show localized alerts, and display inline field errors. Placeholders and unit tests cover supported list, CIDR, IPv6, and wildcard formats.

Changes

API key restriction validation

Layer / File(s) Summary
Restriction validators and tests
portals/devportal/.../constraintValidator.js, portals/devportal/.../constraintValidator.test.js
Added IP/CIDR and referrer-list validators, localized validation dispatch, and parameterized tests for valid and invalid inputs.
Standard API key validation flow
portals/devportal/.../ApiKeyGenerate.jsx, portals/devportal/.../ApiKeyListing.jsx, portals/devportal/.../locales/en.json
Standard key generation validates restrictions, blocks invalid submissions, exposes inline error state, resets errors, and updates placeholders.
Legacy API key validation flow
portals/devportal/.../LegacyApiKeys.jsx, portals/devportal/.../locales/en.json
Legacy key generation applies restriction validation, displays inline and alert errors, resets validation state, and updates localized messages and placeholders.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant APIKeyForm
  participant constraintValidator
  participant Alert
  APIKeyForm->>constraintValidator: validate selected IP or referrer restriction
  constraintValidator-->>APIKeyForm: return localized validation result
  APIKeyForm->>Alert: show error for invalid input
  APIKeyForm-->>APIKeyForm: render inline validation feedback
Loading

Suggested reviewers: ashera96, hisanhunais, piyumaldk

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding API key IP and referrer restriction validation in DevPortal.
Description check ✅ Passed The description is directly related to the code changes and explains the validation behavior, implementation, and tests.
Linked Issues check ✅ Passed The changes implement the requested DevPortal validation for invalid IP and referrer restrictions and surface inline errors.
Out of Scope Changes check ✅ Passed The modified files and locale/test updates all support the restriction validation work and do not appear unrelated.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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

🧹 Nitpick comments (1)
portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx (1)

238-241: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Trim the restriction value for consistency.

In ApiKeyGenerate.jsx, .trim() is applied to the restriction value when constructing the final restrictions payload. Consider applying .trim() here as well to maintain consistency between the standard and legacy key generation flows, preventing strings with leading or trailing whitespaces from being sent to the backend.

♻️ Proposed refactor
         const restrictions = {
-            permittedIP: restrictionType === 'ip' ? restrictionValue : '',
-            permittedReferer: restrictionType === 'referrer' ? restrictionValue : '',
+            permittedIP: restrictionType === 'ip' ? restrictionValue.trim() : '',
+            permittedReferer: restrictionType === 'referrer' ? restrictionValue.trim() : '',
         };
🤖 Prompt for 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.

In
`@portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx`
around lines 238 - 241, Update the restrictions construction in the legacy key
generation flow to trim restrictionValue before assigning permittedIP or
permittedReferer, matching the behavior in ApiKeyGenerate.jsx and ensuring
surrounding whitespace is excluded from the backend payload.
🤖 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.

Nitpick comments:
In
`@portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx`:
- Around line 238-241: Update the restrictions construction in the legacy key
generation flow to trim restrictionValue before assigning permittedIP or
permittedReferer, matching the behavior in ApiKeyGenerate.jsx and ensuring
surrounding whitespace is excluded from the backend payload.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 051c3c9f-2007-456e-8342-aedc7c45e17e

📥 Commits

Reviewing files that changed from the base of the PR and between 19705eb and fb879cf.

📒 Files selected for processing (4)
  • portals/devportal/src/main/webapp/site/public/locales/en.json
  • portals/devportal/src/main/webapp/source/src/app/components/Apis/Details/APIKeys/ApiKeyGenerate.jsx
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/constraintValidator.js

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 18, 2026
- Shorten the comment blocks in constraintValidator and add a doc comment to validateRestrictionOrAlert

@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

🧹 Nitpick comments (2)
portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx (2)

242-245: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Trim restriction values for consistency.

In ApiKeyGenerate.jsx, restrictionValue is trimmed before being added to the restrictions object. Consider trimming it here as well to ensure consistent behavior across both generation flows and to prevent trailing whitespace from being sent in the API payload.

♻️ Proposed refactor
         const restrictions = {
-            permittedIP: restrictionType === 'ip' ? restrictionValue : '',
-            permittedReferer: restrictionType === 'referrer' ? restrictionValue : '',
+            permittedIP: restrictionType === 'ip' ? restrictionValue.trim() : '',
+            permittedReferer: restrictionType === 'referrer' ? restrictionValue.trim() : '',
         };
🤖 Prompt for 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.

In
`@portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx`
around lines 242 - 245, Update the restrictions construction in the legacy API
key generation flow to trim restrictionValue before assigning it to permittedIP
or permittedReferer, matching the behavior in ApiKeyGenerate.jsx and ensuring
whitespace is excluded from the API payload.

69-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider deduplicating validateRestrictionOrAlert.

This helper function appears identical to the one implemented in ApiKeyGenerate.jsx. Consider moving it to a shared utility file (or refactoring the components to just call validateRestrictionValue and handle the UI state themselves) to avoid code duplication.

🤖 Prompt for 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.

In
`@portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx`
around lines 69 - 77, Deduplicate validateRestrictionOrAlert by extracting the
shared validation-and-alert behavior into a common utility, or by having both
components call validateRestrictionValue while handling their own UI state
consistently. Update the implementations in LegacyApiKeys.jsx and
ApiKeyGenerate.jsx to use the shared approach, preserving setRestrictionError,
Alert.error, and boolean return behavior.
🤖 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
`@portals/devportal/src/main/webapp/source/src/app/components/Apis/Details/APIKeys/ApiKeyGenerate.jsx`:
- Line 172: Update the submission flow around validateRestrictionOrAlert to
clear the existing restrictionError before validation or immediately after
successful validation, while preserving the early return for invalid
restrictions so stale inline errors disappear once corrected.

---

Nitpick comments:
In
`@portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx`:
- Around line 242-245: Update the restrictions construction in the legacy API
key generation flow to trim restrictionValue before assigning it to permittedIP
or permittedReferer, matching the behavior in ApiKeyGenerate.jsx and ensuring
whitespace is excluded from the API payload.
- Around line 69-77: Deduplicate validateRestrictionOrAlert by extracting the
shared validation-and-alert behavior into a common utility, or by having both
components call validateRestrictionValue while handling their own UI state
consistently. Update the implementations in LegacyApiKeys.jsx and
ApiKeyGenerate.jsx to use the shared approach, preserving setRestrictionError,
Alert.error, and boolean return behavior.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 177d151b-888e-4d9c-8d21-2b91c7231f86

📥 Commits

Reviewing files that changed from the base of the PR and between fb879cf and 0a6c296.

📒 Files selected for processing (3)
  • portals/devportal/src/main/webapp/source/src/app/components/Apis/Details/APIKeys/ApiKeyGenerate.jsx
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/LegacyApiKeys.jsx
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/constraintValidator.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • portals/devportal/src/main/webapp/source/src/app/components/Shared/AppsAndKeys/constraintValidator.js

@sonarqubecloud

Copy link
Copy Markdown

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.

Missing validation for Security Restrictions (IP Address & Referrer ID) in DevPortal

1 participant