Skip to content

🔒 Fix fallback of allowedOrigin to localhost in production#381

Closed
is0692vs wants to merge 7 commits into
mainfrom
jules-9766932802489647517-7e5e2205
Closed

🔒 Fix fallback of allowedOrigin to localhost in production#381
is0692vs wants to merge 7 commits into
mainfrom
jules-9766932802489647517-7e5e2205

Conversation

@is0692vs

@is0692vs is0692vs commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

🎯 What: The vulnerability fixed
In src/app/api/card/[username]/route.ts, if the APP_URL environment variable is not explicitly set, the allowedOrigin falls back to http://localhost:3000.

⚠️ Risk: The potential impact if left unfixed
This insecure fallback might cause fonts or other internal fetch requests to hit a local developer endpoint instead of the intended service in production environments. Crucially, this variable is used via renderCardResponse as the trusted allowedOrigin in isTrustedFontUrl (in validators.ts), potentially meaning that the production environment would implicitly trust localhost:3000 URLs when it shouldn't.

🛡️ Solution: How the fix addresses the vulnerability
The code now properly verifies the presence of the APP_URL environment variable. If APP_URL is empty and the environment is production, the server now explicitly returns a 500 Server configuration error. In non-production environments, it safely falls back to http://localhost:3000.


PR created automatically by Jules for task 9766932802489647517 started by @is0692vs

Greptile Summary

本番環境で APP_URL が未設定の場合に localhost:3000 へフォールバックしてしまう脆弱性を修正するPRです。APP_URL.trim() を追加してホワイトスペースのみの値も無効と見なすようにし、本番環境では renderErrorCardResponse を使った SVG エラーカード(500)を返すよう変更しています。

  • route.ts: APP_URL の検証を強化し、本番環境では既存のエラーパス(429・404・503)と同形式の SVG エラーレスポンスを返すよう統一。
  • route.test.ts: afterEachvi.unstubAllEnvs() によるクリーンアップを追加し、本番環境かつ APP_URL 未設定のシナリオをカバーする新規テストを追加。

Confidence Score: 5/5

変更範囲は限定的で、既存のエラーハンドリングパターンと一貫した修正です。安全にマージ可能です。

変更内容は GET ハンドラー内の早期リターンロジックの追加と .trim() の適用のみで、既存の正常系・異常系のコードパスには影響しません。前回レビューで指摘されていたレスポンス形式の不整合とエラーメッセージでの内部変数名の露出もいずれも解消されています。

特に注意が必要なファイルはありません。

Important Files Changed

Filename Overview
src/app/api/card/[username]/route.ts APP_URL の欠損チェックを追加。本番環境では renderErrorCardResponse で SVG エラーを返し、trim() でホワイトスペースのみの値も考慮。既存のエラーパスと一貫した形式に統一されている。
src/app/api/card/[username]/route.test.ts afterEach で vi.unstubAllEnvs() を追加し、テスト間の環境変数の汚染を防ぐ。本番環境かつ APP_URL 未設定のシナリオをカバーする新規テストを追加し、status・Cache-Control・renderErrorCardResponse 呼び出し引数を正しく検証している。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[GET /api/card/:username] --> B[Read APP_URL and trim]
    B --> C{allowedOrigin truthy?}
    C -- Yes --> D[Use APP_URL as allowedOrigin]
    C -- No --> E{NODE_ENV is production?}
    E -- Yes --> F[renderErrorCardResponse\nstatus 500 + ERROR_CACHE]
    E -- No --> G[Fallback to localhost:3000]
    G --> D
    D --> H[Build fontUrl from allowedOrigin]
    H --> I{Rate limit exceeded?}
    I -- Yes --> J[renderErrorCardResponse 429]
    I -- No --> K[fetchCardData]
    K -- null --> L[renderErrorCardResponse 404]
    K -- throws --> M[renderErrorCardResponse 503]
    K -- data --> N[renderCardResponse 200]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[GET /api/card/:username] --> B[Read APP_URL and trim]
    B --> C{allowedOrigin truthy?}
    C -- Yes --> D[Use APP_URL as allowedOrigin]
    C -- No --> E{NODE_ENV is production?}
    E -- Yes --> F[renderErrorCardResponse\nstatus 500 + ERROR_CACHE]
    E -- No --> G[Fallback to localhost:3000]
    G --> D
    D --> H[Build fontUrl from allowedOrigin]
    H --> I{Rate limit exceeded?}
    I -- Yes --> J[renderErrorCardResponse 429]
    I -- No --> K[fetchCardData]
    K -- null --> L[renderErrorCardResponse 404]
    K -- throws --> M[renderErrorCardResponse 503]
    K -- data --> N[renderCardResponse 200]
Loading

Reviews (3): Last reviewed commit: "Fix APP_URL environment variable fallbac..." | Re-trigger Greptile

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Jun 12, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jul 13, 2026 1:58am

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@dosubot dosubot Bot added the bug Something isn't working label Jun 12, 2026
@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 17 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 167777c5-90db-4b42-9ab9-f22c49db9574

📥 Commits

Reviewing files that changed from the base of the PR and between a6e198e and 5fab7d2.

📒 Files selected for processing (1)
  • src/app/api/card/[username]/route.test.ts
📝 Walkthrough

Walkthrough

GETハンドラ内でallowedOriginの決定方法を変更した。APP_URL環境変数が未設定の場合、NODE_ENVがproductionであれば500エラーで処理を中断し、それ以外の環境ではlocalhost URLにフォールバックするよう分岐処理を追加した。

Changes

allowedOrigin決定ロジックの修正

Layer / File(s) Summary
環境依存のallowedOriginフォールバック
src/app/api/card/[username]/route.ts
APP_URL未設定時にNODE_ENVをチェックし、production環境では500レスポンスで早期終了、それ以外ではhttp://localhost:3000にフォールバックする分岐ロジックを追加。

Estimated code review effort: 1 (Trivial) | ~5 minutes

Poem

APP_URLが見当たらぬなら
うさぎはピョンと確認するよ 🐰
本番ならば潔く止まり
それ以外はローカルへ跳ねる
小さな分岐、大きな安心

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed 本番環境での allowedOrigin の localhost フォールバック修正を端的に示しており、変更内容と一致しています。
Description check ✅ Passed APP_URL 未設定時の本番環境での挙動修正とセキュリティ影響を説明しており、変更内容と一致しています。
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-9766932802489647517-7e5e2205

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request improves environment variable validation in the card API route by returning a 500 error in production if the APP_URL environment variable is not configured. The reviewer suggested trimming APP_URL to prevent issues with accidental leading or trailing whitespace.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

const url = new URL(request.url);
const options = parseCardQueryParams(url.searchParams);
const allowedOrigin = process.env.APP_URL || "http://localhost:3000";
let allowedOrigin = process.env.APP_URL;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Trimming the APP_URL environment variable prevents potential issues caused by accidental leading or trailing whitespace in configuration files, which could otherwise result in malformed font URLs or failed origin validation checks.

Suggested change
let allowedOrigin = process.env.APP_URL;
let allowedOrigin = process.env.APP_URL?.trim();

@codecov

codecov Bot commented Jun 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/lib/github.ts 41.66% 6 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

Comment thread src/app/api/card/[username]/route.ts
Comment thread src/app/api/card/[username]/route.ts
@pull-request-size pull-request-size Bot added size/M and removed size/XS labels Jul 8, 2026
@is0692vs

is0692vs commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

@greptile review

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/XS and removed size/M labels Jul 8, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@src/app/api/card/`[username]/route.ts:
- Around line 22-23: In the route handler for card rendering, replace the
plain-text production 500 response with the same SVG error fallback used by the
other error paths via renderErrorCardResponse, so the response format stays
consistent for embedded <img> usage. Also remove the internal APP_URL detail
from the message by using a generic server configuration error string, and make
sure the 500 response includes the same Cache-Control behavior as the rest of
the image route; if renderErrorCardResponse needs a fontUrl, update its call or
signature in a way that works without exposing APP_URL.
- Around line 20-26: Add a test for the production-only early return in the card
route when APP_URL is missing. Update the route logic in route.ts’s
allowedOrigin handling only if needed, and cover the branch where
process.env.NODE_ENV is "production" and process.env.APP_URL is unset so the
handler returns a 500 Response with the server configuration error message. Use
the existing route handler symbols in src/app/api/card/[username]/route.ts and
mirror the style of route.test.ts to assert this fallback path directly.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7787d9d2-18dd-4d18-a60c-2911d96f7591

📥 Commits

Reviewing files that changed from the base of the PR and between a475ecb and a6e198e.

📒 Files selected for processing (1)
  • src/app/api/card/[username]/route.ts

Comment thread src/app/api/card/[username]/route.ts
Comment thread src/app/api/card/[username]/route.ts
@is0692vs

Copy link
Copy Markdown
Contributor Author

@greptile review production設定エラーのSVG応答・キャッシュ保持、APP_URLのtrim、production分岐テストを追加しました。再レビューをお願いします。

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Jul 13, 2026
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@is0692vs

Copy link
Copy Markdown
Contributor Author

長期間未整理のPRです。必要なセキュリティ修正は現行mainを起点に最小差分で再作成するため、古いPRとheadブランチを整理します。

@is0692vs is0692vs closed this Jul 13, 2026
@is0692vs is0692vs deleted the jules-9766932802489647517-7e5e2205 branch July 13, 2026 01:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant