Skip to content

fix: ステートレスAPIリクエストでUnexpectedSessionUsageExceptionが発生する問題を修正#6760

Open
kurozumi wants to merge 1 commit into
EC-CUBE:4.3from
kurozumi:fix/stateless-api-unexpected-session-usage
Open

fix: ステートレスAPIリクエストでUnexpectedSessionUsageExceptionが発生する問題を修正#6760
kurozumi wants to merge 1 commit into
EC-CUBE:4.3from
kurozumi:fix/stateless-api-unexpected-session-usage

Conversation

@kurozumi
Copy link
Copy Markdown
Contributor

概要

stateless: true のファイアウォール(/api)に対して認証失敗が発生した際、SecurityListener::onAuthenticationFailure() がセッションに書き込もうとするため UnexpectedSessionUsageException が発生し、500エラーになる問題を修正します。

問題の詳細

EC-CUBE の Api42 プラグインは /api ルートを stateless: true で設定しています。このため、Bearer トークン認証に失敗した場合(例:トークン期限切れ)、本来 401 を返すべきところが 500 になります。

エラーログ:

request.CRITICAL: Uncaught PHP Exception
Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageException:
"Session was used while the request was declared stateless."
at AbstractSessionListener.php line 224
[POST, /api, ...]

原因:

SecurityListener::onAuthenticationFailure() は、フロント用ログインフォームの「ログイン状態を保持する」チェックボックスの値をセッションに保存するために書かれたコードです。しかしこのリスナーは API からの認証失敗でも呼ばれるため、ステートレスリクエストでセッションに書き込もうとして例外が発生します。

修正内容

セッションが未開始の場合(=ステートレスリクエスト)は早期リターンすることで、API リクエストが正しく 401 を返すようにしました。

public function onAuthenticationFailure(LoginFailureEvent $event)
{
    $request = $this->requestStack->getCurrentRequest();
    if (!$request->hasSession() || !$request->getSession()->isStarted()) {
        return;
    }
    $request->getSession()->set('_security.login_memory', (bool) $request->request->get('login_memory', 0));
}

影響範囲

  • フロントのログイン機能には影響なし(セッションが開始済みの場合は従来通り動作)
  • Api42 プラグイン使用時の Bearer トークン認証が正常化される

stateless: trueのファイアウォール(/api)で認証失敗が発生した際、
SecurityListenerのonAuthenticationFailureがセッションに書き込もうとするため
Symfony\Component\HttpKernel\Exception\UnexpectedSessionUsageExceptionが発生し
500エラーになる問題を修正する。

セッションが未開始の場合はスキップすることで、Bearer token認証の
APIリクエストが401を正しく返すようにした。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2451b3ec-2947-4e11-a991-2e87edaca93a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 15, 2026

Codecov Report

❌ Patch coverage is 50.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 78.65%. Comparing base (acc45c2) to head (b0eedb0).
⚠️ Report is 1 commits behind head on 4.3.

Files with missing lines Patch % Lines
src/Eccube/EventListener/SecurityListener.php 50.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##                4.3    #6760      +/-   ##
============================================
- Coverage     78.65%   78.65%   -0.01%     
- Complexity     6825     6827       +2     
============================================
  Files           476      476              
  Lines         27080    27082       +2     
============================================
+ Hits          21300    21301       +1     
- Misses         5780     5781       +1     
Flag Coverage Δ
Unit 78.65% <50.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dotani1111
Copy link
Copy Markdown
Contributor

@kurozumi
PRありがとうございます!
再現と修正確認を進めます。

@dotani1111 dotani1111 added this to the 4.4.0 milestone May 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants