Skip to content

🔒 fix: secure card API endpoint with NextAuth#372

Open
is0692vs wants to merge 1 commit into
mainfrom
fix-card-api-auth-15887205752685383845
Open

🔒 fix: secure card API endpoint with NextAuth#372
is0692vs wants to merge 1 commit into
mainfrom
fix-card-api-auth-15887205752685383845

Conversation

@is0692vs

@is0692vs is0692vs commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

🎯 What: Added NextAuth validation to the /api/card/[username] endpoint and updated associated tests.

⚠️ Risk: The API endpoint was unauthenticated, meaning anyone could potentially misuse it to fetch card data, possibly leading to excessive API requests to GitHub or bypassing intended access controls.

🛡️ Solution:

  1. Removed export const runtime = "edge"; from the route as getServerSession (which relies on Node crypto modules) is unsupported in the Edge runtime.
  2. Imported getAuthenticatedUser from @/lib/apiUtils.
  3. Called await getAuthenticatedUser() to verify the session. If no user is returned, the endpoint immediately responds with a 401 Unauthorized.
  4. Updated the Vitest test file to mock getAuthenticatedUser appropriately so that existing tests continue to pass with the new authentication layer.

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

Greptile Summary

このPRは /api/card/[username] エンドポイントに NextAuth セッション検証を追加し、未認証アクセスを 401 で拒否します。Edge runtime の削除(getServerSession がNodeのcrypto依存のため)も合わせて行われています。

  • getAuthenticatedUser() を呼び出して未認証時に即 401 を返す認証ガードを追加。Edge runtime を Node.js runtime に切り替え。
  • テストに getAuthenticatedUser のモックを追加し既存のキャッシュ・エラーテストを維持。ただし認証が null を返すケース(401パス)のテストが未追加。
  • 認証追加後も Cache-Control: public, s-maxage=1800 ヘッダーが残っており、CDNがレスポンスをキャッシュすることで認証チェックがバイパスされるリスクがある。

Confidence Score: 3/5

認証チェックを追加したものの、public キャッシュヘッダーが残っているため CDN 経由で認証をバイパスできる状態のままマージするのはリスクがある。

追加された認証ガードは Cache-Control: public, s-maxage=1800 と組み合わさると実質的に機能しない。CDN にキャッシュされた後は未認証リクエストにもレスポンスが返り、意図したアクセス制御が守られない。このキャッシュヘッダーの修正が必須であり、マージ前に対応が必要。

src/app/api/card/[username]/route.ts のキャッシュ制御ヘッダーを要確認。

Security Review

  • 認証バイパス(CDNキャッシュ) src/app/api/card/[username]/route.ts: Cache-Control: public, s-maxage=1800 により、認証済みリクエストのレスポンスが CDN にキャッシュされ、その後の未認証リクエストにもキャッシュ済みレスポンスが返される。getAuthenticatedUser() のチェックが実行されないため、追加された認証ガードが実質的に機能しない。

Important Files Changed

Filename Overview
src/app/api/card/[username]/route.ts NextAuth 認証チェックを追加し Edge runtime を削除。ただし public キャッシュヘッダーが残っており CDN 経由で認証をバイパスされる恐れがある。また認証ユーザーのトークンは取得されるが未使用。
src/app/api/card/[username]/route.test.ts getAuthenticatedUser のモックを追加し既存テストを維持。401 パス(未認証時)のテストケースが欠落している。

Sequence Diagram

sequenceDiagram
    participant Client as クライアント(未認証)
    participant CDN as CDN / プロキシ
    participant Route as /api/card/[username]
    participant Auth as getAuthenticatedUser()
    participant GH as GitHub API

    Note over Client,GH: 認証済みユーザーの初回リクエスト
    Client->>CDN: GET /api/card/alice(認証済み)
    CDN->>Route: キャッシュミス → 転送
    Route->>Auth: getAuthenticatedUser()
    Auth-->>Route: "{ username, token }"
    Route->>GH: fetchCardData("alice")
    GH-->>Route: カードデータ
    Route-->>CDN: "200 OK (Cache-Control: public, s-maxage=1800)"
    CDN-->>Client: 200 OK(レスポンスをキャッシュ)

    Note over Client,GH: 未認証ユーザーの後続リクエスト(問題あり)
    Client->>CDN: GET /api/card/alice(未認証)
    CDN-->>Client: 200 OK(キャッシュ済みレスポンスを返す)
    Note right of CDN: Route の認証チェックは実行されない!
Loading

Comments Outside Diff (1)

  1. src/app/api/card/[username]/route.ts, line 11-12 (link)

    P1 security 公開キャッシュヘッダーが認証をバイパスさせる

    public, s-maxage=1800 は CDN・リバースプロキシに「このレスポンスを全ユーザー共有でキャッシュしてよい」と指示します。認証済みユーザーが /api/card/alice を取得すると CDN がキャッシュし、その後に未認証のリクエストが来ても CDN がキャッシュ済みレスポンスを返すため、getAuthenticatedUser() のチェックが一切実行されず認証が完全にバイパスされます。publicprivate に変更するか、CDN キャッシュを無効にする必要があります。

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/app/api/card/[username]/route.ts
    Line: 11-12
    
    Comment:
    **公開キャッシュヘッダーが認証をバイパスさせる**
    
    `public, s-maxage=1800` は CDN・リバースプロキシに「このレスポンスを全ユーザー共有でキャッシュしてよい」と指示します。認証済みユーザーが `/api/card/alice` を取得すると CDN がキャッシュし、その後に未認証のリクエストが来ても CDN がキャッシュ済みレスポンスを返すため、`getAuthenticatedUser()` のチェックが一切実行されず認証が完全にバイパスされます。`public``private` に変更するか、CDN キャッシュを無効にする必要があります。
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
src/app/api/card/[username]/route.ts:11-12
**公開キャッシュヘッダーが認証をバイパスさせる**

`public, s-maxage=1800` は CDN・リバースプロキシに「このレスポンスを全ユーザー共有でキャッシュしてよい」と指示します。認証済みユーザーが `/api/card/alice` を取得すると CDN がキャッシュし、その後に未認証のリクエストが来ても CDN がキャッシュ済みレスポンスを返すため、`getAuthenticatedUser()` のチェックが一切実行されず認証が完全にバイパスされます。`public``private` に変更するか、CDN キャッシュを無効にする必要があります。

### Issue 2 of 3
src/app/api/card/[username]/route.ts:19-22
**`user.token` が取得されているが一切使用されていない**

`getAuthenticatedUser()``{ username, token }` を返しますが、`token` はその後まったく利用されていません。`fetchCardData``process.env.GITHUB_TOKEN` を直接参照するため、認証済みユーザーの OAuth トークンが使われていない状態です。意図的であれば問題ありませんが、`_user` として命名しておくと「意図的に未使用」であることが明示されます。

```suggestion
    const _user = await getAuthenticatedUser();
    if (!_user) {
        return new Response("Unauthorized", { status: 401 });
    }
```

### Issue 3 of 3
src/app/api/card/[username]/route.test.ts:4-10
**401 パスのテストが欠落している**

`getAuthenticatedUser` は常に認証済みユーザーを返すようにモックされていますが、`null` を返した場合(未認証)に `401 Unauthorized` が返されることを確認するテストケースがありません。この PR の主要な変更点であるにもかかわらず、そのパスがテストで検証されていない状態です。`vi.mocked(getAuthenticatedUser).mockResolvedValueOnce(null)` を使って未認証シナリオのテストを追加してください。

Reviews (1): Last reviewed commit: "fix: add authentication to card API endp..." | Re-trigger Greptile

Greptile also left 2 inline comments on this PR.

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 Jun 12, 2026 6:56am

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

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

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

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

⌛ 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3770f447-1af8-4c48-8f58-1e15563c695f

📥 Commits

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

📒 Files selected for processing (2)
  • src/app/api/card/[username]/route.test.ts
  • src/app/api/card/[username]/route.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-card-api-auth-15887205752685383845

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.

@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 introduces authentication checks to the card API route by calling getAuthenticatedUser and returning a 401 Unauthorized response if the user is not authenticated. It also removes the edge runtime configuration and updates the test suite to mock the authentication utility. The review feedback recommends enhancing the mock implementation in the test file by using an async function with an explicit return type to improve type safety and readability.

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.

Comment on lines +4 to +10
vi.mock("@/lib/apiUtils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/apiUtils")>();
return {
...actual,
getAuthenticatedUser: vi.fn().mockResolvedValue({ username: "alice", token: "token" }),
};
});

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

According to the repository guidelines, mock implementations returning Promises should use async functions and have explicit return types to maintain type safety and readability.

Suggested change
vi.mock("@/lib/apiUtils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/apiUtils")>();
return {
...actual,
getAuthenticatedUser: vi.fn().mockResolvedValue({ username: "alice", token: "token" }),
};
});
vi.mock("@/lib/apiUtils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/apiUtils")>();
return {
...actual,
getAuthenticatedUser: vi.fn(async (): Promise<{ username: string; token: string } | null> => ({ username: "alice", token: "token" })),
};
});
References
  1. In TypeScript, ensure functions and mock implementations have explicit return types and use async functions for mocks returning Promises to maintain type safety and readability.

@codecov

codecov Bot commented Jun 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Comment on lines +19 to +22
const user = await getAuthenticatedUser();
if (!user) {
return new Response("Unauthorized", { status: 401 });
}

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.

P2 user.token が取得されているが一切使用されていない

getAuthenticatedUser(){ username, token } を返しますが、token はその後まったく利用されていません。fetchCardDataprocess.env.GITHUB_TOKEN を直接参照するため、認証済みユーザーの OAuth トークンが使われていない状態です。意図的であれば問題ありませんが、_user として命名しておくと「意図的に未使用」であることが明示されます。

Suggested change
const user = await getAuthenticatedUser();
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const _user = await getAuthenticatedUser();
if (!_user) {
return new Response("Unauthorized", { status: 401 });
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/app/api/card/[username]/route.ts
Line: 19-22

Comment:
**`user.token` が取得されているが一切使用されていない**

`getAuthenticatedUser()``{ username, token }` を返しますが、`token` はその後まったく利用されていません。`fetchCardData``process.env.GITHUB_TOKEN` を直接参照するため、認証済みユーザーの OAuth トークンが使われていない状態です。意図的であれば問題ありませんが、`_user` として命名しておくと「意図的に未使用」であることが明示されます。

```suggestion
    const _user = await getAuthenticatedUser();
    if (!_user) {
        return new Response("Unauthorized", { status: 401 });
    }
```

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +4 to +10
vi.mock("@/lib/apiUtils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/apiUtils")>();
return {
...actual,
getAuthenticatedUser: vi.fn().mockResolvedValue({ username: "alice", token: "token" }),
};
});

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.

P2 401 パスのテストが欠落している

getAuthenticatedUser は常に認証済みユーザーを返すようにモックされていますが、null を返した場合(未認証)に 401 Unauthorized が返されることを確認するテストケースがありません。この PR の主要な変更点であるにもかかわらず、そのパスがテストで検証されていない状態です。vi.mocked(getAuthenticatedUser).mockResolvedValueOnce(null) を使って未認証シナリオのテストを追加してください。

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/app/api/card/[username]/route.test.ts
Line: 4-10

Comment:
**401 パスのテストが欠落している**

`getAuthenticatedUser` は常に認証済みユーザーを返すようにモックされていますが、`null` を返した場合(未認証)に `401 Unauthorized` が返されることを確認するテストケースがありません。この PR の主要な変更点であるにもかかわらず、そのパスがテストで検証されていない状態です。`vi.mocked(getAuthenticatedUser).mockResolvedValueOnce(null)` を使って未認証シナリオのテストを追加してください。

How can I resolve this? If you propose a fix, please make it concise.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant