Skip to content

feat: Keycloak 認証基盤セットアップ(Docker Compose) - #36

Merged
susumutomita merged 2 commits into
mainfrom
feat/keycloak-setup
Nov 13, 2025
Merged

susumutomita merged 2 commits into
mainfrom
feat/keycloak-setup

Conversation

@susumutomita

@susumutomita susumutomita commented Nov 11, 2025 •

Copy link
Copy Markdown
Owner

概要

TenkaCloud のマルチテナント認証基盤として Keycloak をセットアップしました。

変更内容

Docker Compose 環境

  • ✅ Keycloak 23.0 コンテナ定義
  • ✅ PostgreSQL 16 Alpine コンテナ定義
  • ✅ ネットワーク分離設定
  • ✅ データ永続化ボリューム設定
  • ✅ ヘルスチェック設定(両サービス)

環境変数設定

  • ✅ .env.example 作成
    • Keycloak 管理者認証情報
    • PostgreSQL 接続情報
    • NextAuth.js 統合用環境変数

ドキュメント

  • ✅ セットアップ手順 README.md
    • クイックスタートガイド
    • Realm/Client/Role 設計
    • 初期設定手順
    • NextAuth.js 統合手順
    • トラブルシューティング

セキュリティ

  • ✅ .gitignore 追加(環境変数ファイル除外)

技術スタック

  • Keycloak 23.0: OSS Identity Provider (OIDC/SAML サポート)
  • PostgreSQL 16 Alpine: Keycloak データベース
  • Docker Compose: ローカル開発環境

Realm 設計

Master Realm

  • Keycloak 管理用のデフォルト Realm
  • 使用禁止: アプリケーションユーザーは登録しない

TenkaCloud Realm

  • TenkaCloud アプリケーション用の Realm
  • すべてのテナント・ユーザーを管理

ロール設計

Role 説明 権限
platform-admin TenkaCloud 全体の管理者 テナント作成・削除、グローバル設定
tenant-admin テナント管理者 ユーザー管理、バトル作成・管理
user 一般ユーザー バトル参加、プロフィール編集

クイックスタート

cd infrastructure/docker/keycloak
cp .env.example .env
# .env を編集してパスワードを変更

docker compose up -d

# http://localhost:8080 にアクセス

検証

  • ✅ Docker Compose 設定ファイルの構文検証
  • ✅ Git にコミット

次のステップ

  • Keycloak の初期設定(Realm/Client/Role 作成)
  • Next.js と Keycloak の認証統合(NextAuth.js)

参照

  • Plan.md の "Keycloak 認証基盤セットアップ - 2025-11-11"
  • infrastructure/docker/keycloak/README.md

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Established Keycloak-based authentication infrastructure with multi-tenant support and role-based access control
  • Chores

    • Configured Docker Compose development environment for local Keycloak and PostgreSQL setup
    • Added security-focused configuration to prevent accidental tracking of sensitive files
  • Documentation

    • Provided comprehensive setup guide including realm design, client configuration, and OIDC integration guidance with Control Plane UI

- Docker Compose ファイル作成(Keycloak 23.0 + PostgreSQL 16)
  - ヘルスチェック設定
  - データ永続化ボリューム
  - ネットワーク分離
- 環境変数サンプルファイル (.env.example)
  - Keycloak 管理者認証情報
  - PostgreSQL 接続設定
  - NextAuth.js 統合用環境変数
- セットアップ手順ドキュメント (README.md)
  - クイックスタートガイド
  - Realm/Client/Role 設計
  - 初期設定手順
  - NextAuth.js 統合手順
  - トラブルシューティング
- .gitignore 追加(環境変数ファイル除外)

技術スタック:
- Keycloak: OSS Identity Provider (OIDC/SAML)
- PostgreSQL: Keycloak データベース
- Docker Compose: ローカル開発環境

Refs: Plan.md "Keycloak 認証基盤セットアップ - 2025-11-11"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 11, 2025 •

Copy link
Copy Markdown

Walkthrough

The PR introduces a complete Keycloak authentication foundation setup including comprehensive planning documentation, Docker Compose orchestration for Keycloak and PostgreSQL, configuration templates, and operational guidance for multi-tenant OIDC integration with NextAuth.js.

Changes

Cohort / File(s) Summary
Planning & Documentation
Plan.md, infrastructure/docker/keycloak/README.md
Adds Keycloak setup plan with objectives, tech stack, TODOs, realm design (Master + TenkaCloud with roles), and operational documentation covering quick-start, realm configuration, NextAuth.js integration, health checks, and troubleshooting.
Docker Infrastructure
infrastructure/docker/keycloak/docker-compose.yml
Defines multi-service orchestration with PostgreSQL 16 (persistent volume, healthcheck) and Keycloak 23.0 (dev mode, admin credentials, DB config, OIDC settings). Includes keycloak-network and postgres_data volume with service dependencies and health probes.
Configuration & Ignore Rules
infrastructure/docker/keycloak/.env.example, infrastructure/docker/keycloak/.gitignore
Introduces environment variable template for Keycloak admin, PostgreSQL, NextAuth.js, and OIDC provider settings; adds gitignore rules for .env file and postgres_data/ volume.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

  • docker-compose.yml deserves focused attention for:
    • Keycloak service dev mode configuration and startup behavior
    • Health check probe configuration (intervals, retries, success criteria)
    • Service dependency ordering via depends_on: service_healthy
    • Volume persistence and network routing correctness
  • Documentation and configuration files are straightforward additions with minimal interdependencies

Poem

🐰 A burrow of security, now complete—
Keycloak's keys and realms now meet,
Docker orchestrates with grace and care,
Multi-tenant realms float through the air,
NextAuth.js and OIDC in perfect pair! 🔐

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly describes the main change: setting up Keycloak authentication foundation using Docker Compose, which matches the primary objective of the pull request.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/keycloak-setup

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.

- 文末の句点を追加
- 「完全に」という絶対的表現を削除
@claude

claude Bot commented Nov 11, 2025

Copy link
Copy Markdown

コードレビュー - Keycloak 認証基盤セットアップ

CLAUDE.md の開発プレイブックに基づいてレビューしました。全体的によく設計されていますが、いくつか改善点があります。

✅ 良い点

  1. 適切なアーキテクチャ選択

    • OSS の Keycloak を選択し、クラウドベンダーロックインを回避
    • PostgreSQL をバックエンドとして採用し、本番環境に対応
    • マルチテナント対応の Realm 設計が明確
  2. セキュリティ考慮

    • .gitignore で .env ファイルを除外
    • .env.example でパスワード変更を促す文言
    • ヘルスチェック設定が適切
  3. ドキュメント品質

    • README.md が詳細で分かりやすい
    • Realm/Role 設計が明確に記述
    • トラブルシューティングガイドが充実
  4. Plan.md の記録

    • 意思決定プロセスが適切に記録されている
    • 進捗ログがタイムスタンプ付きで記録

🔴 Critical Issues(修正必須)

1. 本番環境での重大なセキュリティリスク

docker-compose.yml:24

command: start-dev

問題: start-dev は開発モードで、本番環境では使用すべきではありません。

リスク:

  • HTTPS が無効(HTTP のみ)
  • セキュリティ機能が一部無効化
  • パフォーマンス最適化が無効

推奨: 環境変数で切り替え可能にする、または README に本番環境での注意事項を明記してください。


2. デフォルトパスワードの脆弱性

docker-compose.yml:9, 28, 34

問題: デフォルト値が脆弱すぎる(keycloak_password, admin_password)

推奨: デフォルト値を削除し、環境変数が必須であることを強制するか、README.md に「必ず変更すること」という強い警告を追加してください。


🟡 High Priority(強く推奨)

3. HTTPS の欠如

docker-compose.yml:39

KC_HTTP_ENABLED: true

問題: 認証情報が平文で送信される

推奨:

  • ローカル開発環境でも HTTPS を有効化(自己署名証明書)
  • または、README に「本番環境では必ず HTTPS を使用すること」を明記
  • nginx や Traefik などのリバースプロキシ設定例を追加

4. PostgreSQL のバージョン固定が不十分

docker-compose.yml:3

image: postgres:16-alpine

問題: マイナーバージョンが固定されていない(16.1 → 16.2 で非互換が起きる可能性)

推奨: 具体的なバージョンを指定

image: postgres:16.3-alpine

5. Keycloak のバージョンが古い

docker-compose.yml:21

image: quay.io/keycloak/keycloak:23.0

問題: Keycloak 23.0 は 2023 年末にリリースされ、現在は 25.x が最新

推奨:

  • Keycloak 24.x または 25.x にアップグレード
  • セキュリティパッチが含まれる最新版を使用
  • Plan.md の「未解決の質問」にあるバージョン選択を決定

🟢 Medium Priority(改善推奨)

6. 環境変数の命名規則の不統一

.env.example:11-12

KC_HOSTNAME=localhost
KEYCLOAK_PORT=8080

問題: KC_ と KEYCLOAK_ が混在

推奨: Keycloak 公式の環境変数プレフィックス KC_ に統一

KC_HOSTNAME=localhost
KC_HTTP_PORT=8080

7. ヘルスチェックの curl 依存

docker-compose.yml:51

test: ['CMD-SHELL', 'curl -f http://localhost:8080/health/ready || exit 1']

問題: Keycloak イメージに curl が含まれていない場合、ヘルスチェックが失敗する可能性

推奨: Keycloak 23.0 イメージに curl が含まれていることを確認するか、より信頼性の高い方法(TCP チェック)を検討してください。


8. リソース制限の欠如

docker-compose.yml

問題: メモリやCPUの制限が設定されていない

推奨: リソース制限を追加

deploy:
  resources:
    limits:
      cpus: '1.0'
      memory: 1G
    reservations:
      cpus: '0.5'
      memory: 512M

9. データベースバックアップの言及がない

問題: PostgreSQL のデータバックアップ戦略が README に記載されていない

推奨: README にバックアップセクションを追加

# データベースバックアップ
docker exec tenkacloud-keycloak-db pg_dump -U keycloak keycloak > backup.sql

# リストア
docker exec -i tenkacloud-keycloak-db psql -U keycloak keycloak < backup.sql

🔵 Low Priority(将来の改善)

10. Plan.md の「未解決の質問」が未回答

Plan.md:610-614

問題: 以下の質問が未解決

  • Keycloak のバージョン: 23.x vs 24.x
  • Realm 設計: マスター Realm のみ vs テナント別 Realm
  • Client Secret の管理方法
  • セッションストア: メモリ vs Redis
  • MFA を最初から有効化するか

推奨: これらの決定を Plan.md に記録し、振り返りセクションを完成させてください。


11. テストの欠如

問題: CLAUDE.md では「テストファースト原則」と「カバレッジ 100%」を要求していますが、テストがありません。

推奨: 以下のテストを追加

  • Docker Compose の構文検証テスト
  • Keycloak 起動確認テスト
  • OIDC トークン取得テスト(統合テスト)

例:

# テストスクリプト例
#!/bin/bash
set -e

# 起動テスト
docker compose up -d
sleep 60

# ヘルスチェック
curl -f http://localhost:8080/health/ready

# 管理コンソールログインテスト
# (Keycloak Admin CLI を使用)

docker compose down -v

📋 チェックリスト(CLAUDE.md セルフレビュープロトコル)

  • ❌ lint: 該当ファイルなし(構成ファイルのみ)
  • ❌ typecheck: 該当ファイルなし
  • ❌ test: テストが存在しない(Critical Issue)
  • ❌ test:coverage: テストが存在しない
  • ⚠️ build: Docker Compose の構文は正しいが、実際の起動確認が必要
  • ❌ CI が Green: CI ステータス未確認

CLAUDE.md では「すべて Green にならない限り次に進まない」とありますが、現状ではテストが不足しています。


🎯 推奨アクションアイテム

即座に対応すべき項目(マージ前):

  1. デフォルトパスワードの削除または強い警告追加(Critical)
  2. start-dev の本番利用リスクを README に明記(Critical)
  3. PostgreSQL のバージョン固定(High)
  4. Keycloak のバージョンアップ検討(High)

マージ後に対応する項目:

  1. HTTPS 設定の追加(別 PR)
  2. テストスクリプトの作成(別 PR)
  3. リソース制限の追加(別 PR)
  4. Plan.md の「未解決の質問」を解決(別 PR)

総評

Keycloak 認証基盤のセットアップとして、アーキテクチャ設計とドキュメントは優れています。ただし、CLAUDE.md の「検証プロトコル」に従うと、テストが存在せず、CI が未確認であるため、現状ではマージ条件を満たしていません。

マージ前に最低限必要なこと:

  1. デフォルトパスワードのセキュリティ改善
  2. 本番環境での start-dev 使用リスクを README に明記
  3. Docker Compose の起動確認テスト(手動でも可)
  4. CI ステータスの確認

これらが完了すれば、マージ可能な品質になると考えます。その後、HTTPS 対応やテスト自動化を別 PR で進めることを推奨します。


🤖 このレビューは CLAUDE.md の開発プレイブックに基づいて実施されました。

@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: 0

🧹 Nitpick comments (6)
infrastructure/docker/keycloak/.env.example (2)

1-21: Consider reordering environment variables by logical grouping.

The static analysis tool (dotenv-linter) suggests reordering keys. While this is primarily a style concern, consider grouping related variables together for consistency with tool expectations and readability.

Apply this diff to reorder variables:

  # PostgreSQL Database Configuration
  POSTGRES_DB=keycloak
- POSTGRES_USER=keycloak
  POSTGRES_PASSWORD=change_this_password_in_production
+ POSTGRES_USER=keycloak
  
  # Keycloak Hostname Configuration
  KC_HOSTNAME=localhost
  KEYCLOAK_PORT=8080
  
  # NextAuth.js Configuration (for Control Plane UI)
- NEXTAUTH_URL=http://localhost:3000
  NEXTAUTH_SECRET=generate_random_secret_32_chars_minimum
+ NEXTAUTH_URL=http://localhost:3000

2-3: Add guidance on password requirements.

Default password placeholders are helpful, but consider adding a comment specifying minimum password requirements (e.g., 8+ characters, mixed case, numbers) to align with the production security guidelines mentioned in Plan.md.

Example update:

  # Keycloak Admin Console Credentials
  KEYCLOAK_ADMIN=admin
- KEYCLOAK_ADMIN_PASSWORD=change_this_password_in_production
+ KEYCLOAK_ADMIN_PASSWORD=change_this_password_in_production
+ # Note: Minimum 8 characters, mix of uppercase, lowercase, numbers, and symbols

Also applies to: 7-8

infrastructure/docker/keycloak/docker-compose.yml (1)

24-24: Document dev-mode limitations for clarity.

The configuration uses start-dev mode and sets KC_HOSTNAME_STRICT=false, both appropriate for local development. However, these should be called out in the README or comments as dev-only settings that must change for production use. The PR README mentions this briefly but could be more prominent.

Consider adding an inline comment in the docker-compose.yml:

  command: start-dev
+   # Note: start-dev mode is for development only. Use 'start' for production.

Verify in the README that production deployment warnings are clear (they appear to be in the README, so this is a lower priority).

Also applies to: 38-39

infrastructure/docker/keycloak/README.md (2)

28-32: Add language specifier to code block.

The static analysis tool flags the unmarked code block as missing a language specifier. Add bash to make it explicit.

Apply this diff:

  デフォルトの管理者アカウント。
  
- ```
+ ```bash
  http://localhost:8080
- ```
+ ```

Note: This appears to be a display-only URL block rather than a command to execute. Consider using inline code or plain text instead if it's not meant to be executable.


132-143: NextAuth.js integration section references files not yet in this PR.

The section mentions updating "Control Plane UI .env.local" but the control-plane-ui application is not included in this PR. This is appropriate for a phased rollout, but consider adding a note that this step is deferred to a follow-up PR.

Example addition:

  ## 🔐 NextAuth.js 統合
  
+ **Note**: This integration is completed in a follow-up PR (frontend/control-plane-ui setup).
+ 
  Control Plane UI の `.env.local` に以下を追加。
Plan.md (1)

480-506: Plan TODO list is comprehensive but should clarify PR scope.

The TODOs span multiple phases (docker-compose, initialization scripts, NextAuth.js integration). This PR addresses only the first phase (docker-compose infrastructure). Consider adding a comment indicating which TODOs are in-scope for this PR vs. follow-up work.

Example:

  **タスク (TODOs)**:
+ *This PR addresses Docker Compose setup (✓ completed). Remaining items planned for follow-up PRs.*
- [ ] Docker Compose ファイル作成(Keycloak + PostgreSQL)
+ [x] Docker Compose ファイル作成(Keycloak + PostgreSQL)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b87be30 and 40b0819.

📒 Files selected for processing (5)
  • Plan.md (1 hunks)
  • infrastructure/docker/keycloak/.env.example (1 hunks)
  • infrastructure/docker/keycloak/.gitignore (1 hunks)
  • infrastructure/docker/keycloak/README.md (1 hunks)
  • infrastructure/docker/keycloak/docker-compose.yml (1 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
infrastructure/docker/keycloak/.env.example

[warning] 8-8: [UnorderedKey] The POSTGRES_PASSWORD key should go before the POSTGRES_USER key

(UnorderedKey)


[warning] 16-16: [UnorderedKey] The NEXTAUTH_SECRET key should go before the NEXTAUTH_URL key

(UnorderedKey)

🪛 markdownlint-cli2 (0.18.1)
infrastructure/docker/keycloak/README.md

30-30: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

Plan.md

508-508: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (7)
infrastructure/docker/keycloak/.gitignore (1)

1-5: Appropriate security exclusions in place.

The file correctly excludes environment variables containing secrets and Docker volume data from version control. No concerns.

infrastructure/docker/keycloak/docker-compose.yml (1)

1-63: Docker Compose configuration is well-structured and production-ready for local development.

The setup correctly defines service dependencies, health checks, and networking. Key strengths:

  • Service dependency chain (depends_on: service_healthy) ensures correct startup order
  • Persistent volume for PostgreSQL data
  • Appropriate health check configurations with sufficient timeouts
  • Environment variable defaults align with .env.example
infrastructure/docker/keycloak/README.md (1)

89-130: Initial setup instructions are clear and comprehensive.

The step-by-step guide for creating the TenkaCloud Realm, Client, Roles, and test users is well-documented and matches the Plan.md design. No corrections needed.

Plan.md (4)

618-635: Progress log accurately reflects PR completion status.

The log documents the actual work completed in this PR (docker-compose.yml, .env.example, README.md, .gitignore) with timestamps. The unchecked TODOs appropriately reflect remaining work for follow-up PRs (realm initialization, NextAuth.js integration in the UI app).


554-578: Environment variable design aligns with implementation files.

The environment variable specifications match .env.example and docker-compose.yml precisely. All variables are documented with clear purposes and default values. Good cross-file consistency.


536-553: Keycloak Realm design in Plan matches README and is well-articulated.

The realm design (Master Realm, TenkaCloud Realm) with roles (platform-admin, tenant-admin, user) is documented consistently across Plan.md and README.md. No corrections needed.


507-534: No path correction needed at line 519.

The directory frontend/control-plane/ shown at line 519 is correct—the directory actually exists in the codebase. The inconsistency lies elsewhere: the TODO section references frontend/control-plane-ui/ (around line 316), which should be frontend/control-plane/ to match the actual directory and the directory structure shown later in the document. The -ui suffix is only the Keycloak CLIENT ID, not the directory name.

Likely an incorrect or invalid review comment.

@susumutomita
susumutomita merged commit 5ab496d into main Nov 13, 2025
8 checks passed
@susumutomita
susumutomita deleted the feat/keycloak-setup branch November 13, 2025 00:11
susumutomita added a commit that referenced this pull request May 17, 2026
audit table #10: Home に問題詳細 ProblemPanel を全部 embed していた (= image #36 で
hello-world の full info がホームに表示)。 これは 「一等地に何を出すか」 のティアリング違反。
ホームは dashboard (= score 集計 + 残タスク 概観 + 詳細への導線) で、 問題の deep dive は
/problems から行う。

audit table #11: 「ようこそ、{超長 username} さん」 で header が overflow していた (=
image #36 の '0123456789012...' が全幅占有)。 24 文字 (= 半角換算) を超える username は
'…' で truncate。 fullName は detail / profile 画面で出す経路で対応 (= 別 PR)。

修正:
- Home.tsx: `view?.problems.map((p) => <ProblemPanel .../>)` ブロックを削除、
  代わりに 「問題に挑戦」 quick link container を表示 → /problems に navigate
- `truncateTeamName` helper (= 24 文字超を '…' で切る) を追加
- i18n ja / en に `quests_quick_link_*` 3 keys を追加

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
susumutomita added a commit that referenced this pull request May 17, 2026
epic #952 / #956 Phase 1: 直近 audit (image #29 / #32-#36 / #43 / #45 / #50 等)
で表面 UX を 1 件ずつ修正してきたが、 画面ごとの IA を体系的に見直して
いなかった。 5 persona (Participant / TenantAdmin / TenantOperator /
TenantViewer / SystemAdmin) × 12 主要 screen の primary/secondary/non-target
を 1 表で正本化する。

新規 docs/ux/persona-screen-matrix.html:
- Persona 一覧: 主役の状況 / 典型タスク / 絶対に見せない情報
- Screen × Persona 行列: 12 screen × 5 persona の primary action
- 情報のティアリング規約: 一等地 / 中段 / 下段に何を入れるか
- エラー / 空状態 UX 規約: FriendlyErrorAlert の 4 要素 + 空状態 = 次の一歩
- Cloudscape 使い方規約: Header / Container / Table-vs-Cards / Button variant
- Roadmap: Phase 1 = 本 PR / Phase 2 = primary action 統一 (画面ごとに別 PR)
  / Phase 3 = FriendlyErrorAlert を全 SPA 展開 / Phase 4 = ADR 化

設計判断:
- HTML 直書き (= ADR と同じ理由で表現力 / row span / color を保つ。
  feedback_design_docs_html メモリに沿う)
- docs/ux/ を新設 (= 既存の docs/operations/ docs/problems/ と並列に)
- 機械検査 ルール (= harness) は Phase 4 (= ADR 化) で追加。 本 doc は
  reference として配布する段階

Relates #956 Phase 1
Relates #952

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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