Skip to content

feat(auth): enhance IP restriction handling with CIDR support - #2445

Merged
Calcium-Ion merged 2 commits into
mainfrom
feat/token-ip-whitelist-cidr
Dec 15, 2025
Merged

feat(auth): enhance IP restriction handling with CIDR support#2445
Calcium-Ion merged 2 commits into
mainfrom
feat/token-ip-whitelist-cidr

Conversation

@Calcium-Ion

@Calcium-Ion Calcium-Ion commented Dec 15, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • IP allowlist now accepts CIDR notation for more flexible network-level access control.
  • Improvements

    • UI labels and translations updated across languages to clarify CIDR support.
    • Expanded security warnings recommending use with gateway solutions (nginx, CDN).
    • Stricter IP validation and membership checks for more reliable enforcement of IP restrictions.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Centralized IP utilities and added CIDR-aware matching; removed duplicate IsIP. Token model now returns an IP slice. Auth middleware validates parsed client IP and enforces CIDR-based allowlist checks. SSRF protection delegates to the new CIDR helper. UI labels and translations updated to indicate CIDR support and gateway guidance.

Changes

Cohort / File(s) Summary
IP Utilities
common/ip.go, common/utils.go
Added IsIP(s string) bool, ParseIP(s string) net.IP, and IsIpInCIDRList(ip net.IP, cidrList []string) bool in common/ip.go. Removed duplicate IsIP from common/utils.go.
SSRF Protection
common/ssrf_protection.go
Replaced inline CIDR/single-IP matching with a call to IsIpInCIDRList() in isIPListed().
Auth Middleware
middleware/auth.go
Switched from GetIpLimitsMap() to GetIpLimits(); added client IP parsing (net.ParseIP), aborts on invalid IP, enforces allowlist via IsIpInCIDRList(), and added debug logging.
Token Model
model/token.go
Renamed GetIpLimitsMap()GetIpLimits() and changed return type from map[string]any to []string, returning a cleaned slice of allowed IP strings.
Frontend - Token Modal
web/src/components/table/tokens/modals/EditTokenModal.jsx
Updated IP allowlist label to "IP白名单(支持CIDR表达式)" and expanded helper text to recommend using gateways (nginx/CDN).
I18n Locales
web/src/i18n/locales/{en,fr,ja,ru,vi,zh}.json
Updated translations for the IP whitelist label to include CIDR support and expanded the warning to suggest using gateways (nginx/CDN) across listed locales.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Areas needing extra attention:
    • IsIpInCIDRList() parsing logic and its fallback to single-IP equality
    • Auth middleware: early abort behavior on invalid IPs and logging placement
    • GetIpLimits() signature change and all call sites for type compatibility
    • Locale key/value consistency across language files and UI rendering

Suggested reviewers

  • seefs001

Poem

🐰 A nibble, a hop, a CIDR in sight,
I tied IPs in ranges neat and tight.
From maps to lists, the checks now flow,
Gateways watch while my whiskers glow.
Hop on—security’s feeling light! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: enhancing IP restriction handling by adding CIDR support, which is the primary objective reflected across backend utility functions, middleware authentication, and frontend UI/i18n updates.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/token-ip-whitelist-cidr

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3959305 and e16e7d6.

📒 Files selected for processing (1)
  • middleware/auth.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
middleware/auth.go (2)
logger/logger.go (1)
  • LogDebug (69-76)
common/ip.go (2)
  • ParseIP (10-12)
  • IsIpInCIDRList (33-51)

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

🧹 Nitpick comments (4)
common/ip.go (1)

33-50: CIDR + single‑IP matching logic is correct; consider minor naming cleanup

IsIpInCIDRList correctly:

  • treats each item as CIDR first and falls back to exact IP match on parse failure,
  • safely ignores malformed entries.

You might optionally rename it to IsIPInCIDRList for consistency with IsIP and to match Go’s usual acronym casing, but this is non‑blocking.

model/token.go (1)

37-57: GetIpLimits behavior is sound; small cleanups are optional

The method:

  • Safely handles nil / empty AllowIps,
  • Normalizes and filters out empty entries,
  • Leaves actual validation to the shared CIDR helper.

If you want to simplify later, you could drop the global ReplaceAll(*token.AllowIps, " ", "") and just trim per line, but current logic is functionally fine.

web/src/i18n/locales/fr.json (1)

1765-1765: Minor French style & capitalization improvement for the warning

Current text is correct but can read a bit more natural in French and normalize “Nginx/CDN” capitalization.

-    "请勿过度信任此功能,IP可能被伪造,请配合nginx和cdn等网关使用": "Ne faites pas trop confiance à cette fonctionnalité, l'IP peut être usurpée, veuillez l'utiliser en conjonction avec des passerelles telles que nginx et cdn",
+    "请勿过度信任此功能,IP可能被伪造,请配合nginx和cdn等网关使用": "Ne faites pas une confiance excessive à cette fonctionnalité : l’adresse IP peut être usurpée. Utilisez‑la conjointement avec une passerelle (reverse proxy) comme Nginx ou un CDN.",
web/src/i18n/locales/vi.json (1)

1990-1990: Optional improvement to wording and gateway terminology

The translation is understandable and accurate. To improve clarity and match common terminology, you could name reverse proxies/CDN explicitly and capitalize them.

-    "请勿过度信任此功能,IP可能被伪造,请配合nginx和cdn等网关使用": "Đừng quá tin tưởng tính năng này, IP có thể bị giả mạo, vui lòng sử dụng cùng với nginx và các cổng khác như cdn",
+    "请勿过度信任此功能,IP可能被伪造,请配合nginx和cdn等网关使用": "Đừng quá tin tưởng tính năng này, IP có thể bị giả mạo, vui lòng sử dụng cùng với các gateway/ngược proxy như Nginx hoặc một CDN.",
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ea8cbd and 3959305.

📒 Files selected for processing (12)
  • common/ip.go (2 hunks)
  • common/ssrf_protection.go (1 hunks)
  • common/utils.go (0 hunks)
  • middleware/auth.go (2 hunks)
  • model/token.go (1 hunks)
  • web/src/components/table/tokens/modals/EditTokenModal.jsx (1 hunks)
  • web/src/i18n/locales/en.json (2 hunks)
  • web/src/i18n/locales/fr.json (2 hunks)
  • web/src/i18n/locales/ja.json (2 hunks)
  • web/src/i18n/locales/ru.json (2 hunks)
  • web/src/i18n/locales/vi.json (2 hunks)
  • web/src/i18n/locales/zh.json (2 hunks)
💤 Files with no reviewable changes (1)
  • common/utils.go
🧰 Additional context used
🧬 Code graph analysis (1)
middleware/auth.go (2)
logger/logger.go (1)
  • LogDebug (69-76)
common/ip.go (2)
  • ParseIP (10-12)
  • IsIpInCIDRList (33-51)
🔇 Additional comments (9)
common/ip.go (1)

5-12: Centralized IP parse/validate helpers look good

Wrapping net.ParseIP in IsIP / ParseIP is straightforward and keeps IP handling in one place; API and behavior are clear and correct.

common/ssrf_protection.go (1)

184-190: Delegating IP matching to IsIpInCIDRList is a clean refactor

Reusing IsIpInCIDRList keeps SSRF IP allow/deny logic centralized while preserving empty‑list semantics; no issues spotted.

web/src/i18n/locales/ru.json (1)

104-104: RU translations correctly reflect CIDR support and gateway guidance

The updated Russian strings for the IP whitelist label and the spoofing warning accurately capture “CIDR expressions” support and recommend using nginx/CDN gateways; looks consistent with other locales.

Also applies to: 1776-1776

web/src/i18n/locales/ja.json (1)

85-85: JA translations for CIDR label and IP spoofing warning look accurate

IPホワイトリスト(CIDR表記に対応) and the updated caution about spoofable IPs + nginx/CDN gateways read naturally in Japanese and match the intended meaning.

Also applies to: 1672-1672

web/src/i18n/locales/zh.json (1)

98-98: Localization updates properly reflect CIDR support and security guidance.

The Chinese locale updates clearly communicate CIDR notation support and include important security warnings about IP spoofing with gateway integration recommendations.

Also applies to: 1743-1743

web/src/components/table/tokens/modals/EditTokenModal.jsx (1)

560-560: Translation key references are properly implemented using react-i18next.

The form field label and helper text correctly use the t() function to reference the localized strings. The changes maintain consistency with other form fields in the component and properly expose CIDR support information to users.

Please verify that all supported locale files (French, Japanese, Russian, Vietnamese, etc.) have been updated with the corresponding translations for these two keys:

  • "IP白名单(支持CIDR表达式)"
  • "请勿过度信任此功能,IP可能被伪造,请配合nginx和cdn等网关使用"

The enriched summary indicates these updates were made across multiple locales, but this review can only confirm the Chinese and English translations provided.

Also applies to: 564-564

web/src/i18n/locales/en.json (1)

100-100: English translations accurately convey CIDR support messaging and security guidance.

The English translations properly localize both the label update and the expanded security guidance. The messaging is clear, professional, and maintains consistency with the original Chinese intent while using natural English phrasing.

Also applies to: 1755-1755

web/src/i18n/locales/fr.json (1)

102-102: CIDR label translation looks good

The wording is clear, technically accurate, and consistent with the Chinese source; no changes needed.

web/src/i18n/locales/vi.json (1)

85-85: CIDR label translation is accurate

The Vietnamese string correctly conveys IP allowlist semantics and CIDR support; no adjustments needed.

Comment thread middleware/auth.go
@Calcium-Ion
Calcium-Ion merged commit 11593bd into main Dec 15, 2025
1 check was pending
@Calcium-Ion
Calcium-Ion deleted the feat/token-ip-whitelist-cidr branch January 29, 2026 17:10
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
…itelist-cidr

feat(auth): enhance IP restriction handling with CIDR support
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.

1 participant