Skip to content

🔒 [Security] Fix timing attack vulnerability in CSRF bypass secret check#190

Merged
is0692vs merged 5 commits intomainfrom
fix/csrf-timing-attack-secret-16398301044902068021
Mar 22, 2026
Merged

🔒 [Security] Fix timing attack vulnerability in CSRF bypass secret check#190
is0692vs merged 5 commits intomainfrom
fix/csrf-timing-attack-secret-16398301044902068021

Conversation

@is0692vs
Copy link
Copy Markdown
Contributor

@is0692vs is0692vs commented Mar 22, 2026

🎯 What:
Fixed a vulnerability in the CSRF bypass logic where the x-test-auth-secret header was compared to the TEST_AUTH_SECRET environment variable using a standard string equality (===).

⚠️ Risk:
Using a standard equality operator for sensitive strings (like secrets) opens the application to timing attacks. An attacker could theoretically deduce the length and character composition of the secret by measuring the response time of the request. Although this code only runs when NODE_ENV !== "production", having robust checking ensures test environments are not easily compromised.

🛡️ Solution:
Replaced the === comparison with Hono's timingSafeEqual function from hono/utils/buffer. This executes the string comparison in constant time, thus mitigating the timing attack vulnerability. Proper null checks were also introduced to handle missing headers or environment variables safely.


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

Greptile Summary

CSRF バイパス処理における x-test-auth-secret ヘッダーの検証方式を、通常の文字列等値比較(===)から Hono の timingSafeEqual による定数時間比較に置き換えるセキュリティ修正PRです。あわせて null チェックの強化も行われています。

  • 修正内容: testAuthHeader === c.env.TEST_AUTH_SECRETawait timingSafeEqual(testAuthHeader, c.env.TEST_AUTH_SECRET) に置き換え
  • null チェック追加: !!testAuthHeader を追加し、ヘッダーが存在しない場合に timingSafeEqualundefined が渡されるのを防止
  • Hono バージョン: ^4.12.8 を使用。Hono の timingSafeEqual 自体にはセキュリティアドバイザリ(GHSA-gq3j-xvxp-8hrf)が存在したが、4.11.10 で修正済みのため問題なし
  • 内部APIパス: hono/utils/buffer は Hono の内部ユーティリティパスであり、将来のバージョンで変更される可能性がある点に注意
  • 対象スコープ: NODE_ENV !== "production" の場合のみ実行されるテスト環境向けコードであり、本番環境への直接的な影響はない

Confidence Score: 4/5

  • テスト環境向けのセキュリティ修正として正しい改善であり、本番環境への影響もないため安全にマージ可能です。
  • 修正内容は正しく、使用している Hono バージョン(^4.12.8)は timingSafeEqual の既知の脆弱性(GHSA-gq3j-xvxp-8hrf)が修正済みの v4.11.10 以降であるため問題なし。hono/utils/buffer という内部パスの使用と && 短絡評価による微小なタイミング差異が残るが、どちらも実用上の影響は限定的であり、スコア 4 とした。
  • 特に注意が必要なファイルはありませんが、apps/api/src/index.tshono/utils/buffer インポートは将来のバージョンアップ時に確認が必要です。

Important Files Changed

Filename Overview
apps/api/src/index.ts CSRF バイパスのシークレット比較を === から timingSafeEqual に置き換えるセキュリティ修正。null チェックの追加も含む。内部APIパス (hono/utils/buffer) の使用と短絡評価の微小なリスクに注意が必要だが、全体的な改善は正しい。

Sequence Diagram

sequenceDiagram
    participant Client as クライアント
    participant CSRF as CSRFミドルウェア
    participant TSE as timingSafeEqual<br/>(hono/utils/buffer)
    participant Next as 次のハンドラ

    Client->>CSRF: POST /api/* (テスト認証ヘッダー付き)
    CSRF->>CSRF: NODE_ENV チェック
    CSRF->>CSRF: ENABLE_TEST_AUTH チェック
    CSRF->>CSRF: TEST_AUTH_SECRET 存在確認
    CSRF->>CSRF: ヘッダー値の null チェック (新規追加)
    CSRF->>TSE: await timingSafeEqual(header, envValue)
    Note over TSE: 定数時間比較<br/>旧実装: === による非定数時間比較
    TSE-->>CSRF: true / false
    alt isTestEnv = true
        CSRF->>Next: CSRFバイパス → next()
    else isTestEnv = false
        CSRF->>CSRF: Origin / Referer チェック
        alt 許可されたOrigin
            CSRF->>Next: next()
        else 不許可
            CSRF-->>Client: 403 Forbidden
        end
    end
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/api/src/index.ts
Line: 3

Comment:
**内部APIパスの使用について**

`hono/utils/buffer` は Hono の内部ユーティリティパスであり、パブリックAPIとして明示的に保証されているわけではありません。将来の Hono のバージョンアップでこのパスが変更または削除される可能性があります。

Cloudflare Workers 環境(本プロジェクトは `wrangler` を使用)では、ランタイムネイティブな `crypto.subtle.timingSafeEqual` を利用する方法も存在します。ただし、その場合は `TextEncoder` を用いて文字列をバッファに変換し、長さの差異をパディングで吸収する必要があります。

なお、Hono 自身の `timingSafeEqual` にはセキュリティアドバイザリ [GHSA-gq3j-xvxp-8hrf](https://github.com/honojs/hono/security/advisories/GHSA-gq3j-xvxp-8hrf) が存在し、`4.11.10` より前のバージョンでは内部的に `===` を使用していたため真の定数時間比較が行われていませんでした。本プロジェクトでは `^4.12.8` を使用しているため現時点では問題ありませんが、依存関係の更新時にこの点を把握しておくことが重要です。

現状のままでも動作は正しいですが、長期的なメンテナンス性の観点から公開APIへの移行を検討してください。

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

---

This is a comment left during a code review.
Path: apps/api/src/index.ts
Line: 50-53

Comment:
**短絡評価による微小なタイミング差異について**

現在の実装では `&&` による短絡評価が残っています。`!!testAuthHeader``false` の場合(ヘッダー未送信時)は `timingSafeEqual` が呼ばれず処理が早期終了します。

これはシークレットの内容そのものを漏洩するわけではなく(「ヘッダーが存在するかどうか」しか分からない)、実際の影響は非常に限定的です。しかし厳密にタイミング攻撃を防ぐなら、ヘッダーが `null` / `undefined` の場合もダミー文字列と比較して常に `timingSafeEqual` を呼び出すアプローチが考えられます。

現状の実装でも `===` との比較で大幅な改善であり、テスト環境向けのコードとして実用上問題はありませんが、念のため共有します。

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

Last reviewed commit: "fix(api): use timing..."

Greptile also left 2 inline comments on this PR.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 22, 2026

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
open-shelf Ignored Ignored Mar 22, 2026 4:33am

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 22, 2026

Warning

Rate limit exceeded

@is0692vs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 3 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7f398827-d4fd-4c79-a20d-aca7a065a119

📥 Commits

Reviewing files that changed from the base of the PR and between a88054e and b36679d.

📒 Files selected for processing (2)
  • apps/api/src/index.ts
  • apps/api/src/routes/__tests__/csrf.test.ts
📝 Walkthrough

ウォークスルー

CSRF ミドルウェアにおけるテスト環境の認証シークレット検証ロジックを強化しました。SHA-256 ハッシング関数とタイミング安全な文字列比較を新たに追加し、テスト環境の判定条件を厳密化(ENABLE_TEST_AUTH === "true" と非空のシークレット一致が必須)しました。対応するテストケースを追加しています。

変更内容

コホート / ファイル 概要
CSRF ミドルウェアセキュリティ強化
apps/api/src/index.ts
SHA-256 ハッシング関数 (sha256) とタイミング安全な等価性比較関数 (timingSafeEqualString) を追加。テスト認証シークレット検証を、直接的な文字列比較から暗号学的ハッシュと XOR ベースの比較へ変更。isTestEnv 設定条件を ENABLE_TEST_AUTH === "true"、設定済みシークレットの存在、ダイジェストマッチに限定。
CSRF テストケース拡充
apps/api/src/routes/__tests__/csrf.test.ts
x-test-auth-secret ヘッダ欠落時に CSRF リクエストがブロック(HTTP 403)されることを検証する新規テストケースを追加。既存テストロジックに変更なし。

見積もりコード審査工数

🎯 2 (Simple) | ⏱️ ~12 分

関連する可能性のあるプルリクエスト

提案ラベル

size/M

ウサギの詩

🐰 ハッシュの魔法で安全に、
タイミングの精度も守られて、
シークレットは暗号に包まれ、
テスト環境もしっかり認証、
セキュリティの扉、ひときわ固く ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは CSRF バイパスのシークレット比較におけるタイミング攻撃脆弱性の修正について明確に述べており、変更セットの主要な目的を適切に要約しています。
Description check ✅ Passed 説明は CSRF バイパスロジックにおける x-test-auth-secret ヘッダーの検証方式を === から timingSafeEqual に置き換える修正内容を関連性を持って述べており、変更セットに関連しています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/csrf-timing-attack-secret-16398301044902068021

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
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the security posture of the application's CSRF bypass mechanism, particularly in non-production environments. It resolves a potential timing attack vulnerability by ensuring that secret comparisons are performed in a constant-time manner, thereby preventing attackers from inferring sensitive information through response time variations.

Highlights

  • Security Vulnerability Fix: Addressed a timing attack vulnerability in the CSRF bypass logic by replacing a standard string equality comparison (===) with a cryptographically secure, constant-time comparison for the x-test-auth-secret header.
  • Secure Comparison Implementation: Implemented timingSafeEqual from hono/utils/buffer to compare sensitive secrets, ensuring that the comparison takes a consistent amount of time regardless of the input, thus preventing timing attacks.
  • Robustness Improvements: Enhanced the CSRF bypass logic with explicit null checks for the x-test-auth-secret header and TEST_AUTH_SECRET environment variable, improving the robustness and safety of the secret handling.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

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

Choose a reason for hiding this comment

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

Code Review

This PR correctly addresses a timing attack vulnerability in the CSRF bypass check using timingSafeEqual. However, the fix is incomplete as the same vulnerable string comparison is used elsewhere. To fully mitigate this security risk, I recommend also updating the following locations to use a timing-safe comparison: apps/api/src/routes/auth.ts at line 257 (in /api/auth/test-token) and line 332 (in /api/auth/test-org).

Comment thread apps/api/src/index.ts Outdated
Comment thread apps/api/src/index.ts Outdated
Implement custom timingSafeEqual helper using Web Crypto to prevent
timing attacks on the x-test-auth-secret header in the test environment.
The logic ensures constant execution time by always performing the hash
comparison, even when the header is omitted. Included missing test case.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 22, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

@is0692vs
Copy link
Copy Markdown
Contributor Author

メンテナ確認済みです。Botコメント(Codecov / CodeRabbit / Gemini / Jules / Greptile / Vercel)を確認し、現時点で追加対応が必要な指摘はありません。必要な追対応が出た場合はこのPRで反映します。

google-labs-jules Bot and others added 2 commits March 22, 2026 04:33
Implement custom timingSafeEqual helper using Web Crypto to prevent
timing attacks on the x-test-auth-secret header in the test environment.
The logic ensures constant execution time by always performing the hash
comparison, even when the header is omitted. Included missing test case.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 22, 2026

Deployment failed with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/hirokis-projects-afd618c7?upgradeToPro=build-rate-limit

@is0692vs is0692vs merged commit efba5f3 into main Mar 22, 2026
16 of 18 checks passed
@is0692vs is0692vs deleted the fix/csrf-timing-attack-secret-16398301044902068021 branch March 22, 2026 10:53
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