Skip to content

feat: Keycloak セットアップスクリプトの改善とコマンド追加 - #52

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

susumutomita merged 2 commits into
mainfrom
feat/keycloak-setup-improvements

Conversation

@susumutomita

@susumutomita susumutomita commented Nov 21, 2025 •

Copy link
Copy Markdown
Owner

概要

Keycloak のセットアップスクリプトを改善し、Makefile に新しいコマンドを追加しました。

変更内容

  • ✅ Keycloak の起動待機ロジックを改善(最大60秒待機、5秒間隔でチェック)
  • ✅ セットアップスクリプトでレルムとクライアントの存在確認を追加(冪等性の向上)
  • ✅ Makefile に keycloak-setup と keycloak-import コマンドを追加
  • ✅ docker-compose.yml の環境変数を整理

テスト

  • ✅ make keycloak-start でコンテナが正常に起動
  • ✅ make keycloak-setup でレルムとクライアントが作成される
  • ✅ 既存のレルム/クライアントがある場合は処理がスキップされる(冪等性確認)

動作確認

make keycloak-start
make keycloak-setup

技術的な改善点

  1. 起動待機の改善: 単純なsleepから、実際にKeycloakのヘルスチェックを行う方式に変更
  2. 冪等性: レルムやクライアントが既に存在する場合は処理をスキップ
  3. コマンド分離: セットアップ処理を個別のMakefileターゲットとして実行可能に

Summary by CodeRabbit

  • Chores

    • Centralized node runner and frontend directory variables; unified frontend install and CI install flow.
    • Added new CI install and clean targets; redefined common dev/test/build/typecheck targets and added before-commit alias.
    • Updated help text to reflect combined root+frontend workflows and new runners.
    • Added execution plan section documenting the updated before-commit flow.
  • New Features

    • Frontend: added a typecheck script for no-emits TypeScript checks.
    • Keycloak: enable health and metrics, adjusted hostname URL, changed default admin password, and create a default user on setup.

✏️ Tip: You can customize this high-level summary in your review settings.

- Keycloak の起動待機ロジックを改善(最大60秒待機)
- セットアップスクリプトでレルムとクライアントの存在確認を追加
- Makefile に keycloak-setup と keycloak-import コマンドを追加
- docker-compose.yml の環境変数を整理

変更により、Keycloak の初期設定がより確実に実行されるようになりました。

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

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

coderabbitai Bot commented Nov 21, 2025 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

Walkthrough

This PR centralizes Node frontend runners in the root Makefile (adds NODE_RUNNER, BUN, FRONTEND_DIR), moves frontend install/build/typecheck/test targets under that scheme, adds install_ci and clean targets, updates help text, adjusts Keycloak compose env flags, updates Keycloak setup script to change admin password and create a default user, and adds a frontend typecheck npm script.

Changes

Cohort / File(s) Summary
Makefile (root)
Makefile
Add variables NODE_RUNNER, BUN, FRONTEND_DIR; replace direct npm/bun calls with $(NODE_RUNNER)/$(BUN); add install_ci, clean, lint, format, typecheck, build, dev, test, test_coverage, before_commit/before-commit targets; run frontend installs from root and $(FRONTEND_DIR); add SKIP_FRONTEND_BUILD skip flag; update help text.
Keycloak docker config
infrastructure/docker/keycloak/docker-compose.yml
Replace KC_HOSTNAME with KC_HOSTNAME_URL: "http://localhost:8080"; add KC_HEALTH_ENABLED: true and KC_METRICS_ENABLED: true; retain other env/ports.
Keycloak init script
infrastructure/docker/keycloak/scripts/setup-keycloak.sh
Change admin password from "admin" to "admin_password"; add conditional creation of a default user (user) with credentials if missing (fetch user id, create user, set password), with logging.
Plan / docs
Plan.md
Add exec plan section "make before-commit フロー修正 - 2025-11-21" with objective, guardrails, TODOs, validation steps, progress log, and retrospective stub.
Frontend package.json
frontend/control-plane/package.json
Add typecheck npm script: tsc --noEmit.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Dev as Developer
  participant Make as Makefile
  participant Node as Node runner ($(NODE_RUNNER)/$(BUN))
  participant Frontend as Frontend (frontend/control-plane)

  rect rgb(230, 248, 230)
    Dev->>Make: make before-commit
    Make->>Make: run lint_text, format_check
    Make->>Node: $(NODE_RUNNER) run typecheck (in $(FRONTEND_DIR))
    Node-->>Make: typecheck result
    alt SKIP_FRONTEND_BUILD not set
      Make->>Node: $(NODE_RUNNER) run build (in $(FRONTEND_DIR))
      Node-->>Make: build result
    end
    Make-->>Dev: aggregated status
  end

  note right of Node `#f8f0d6`: install_ci / install targets run\n$(BUN) install at root and in $(FRONTEND_DIR)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pay extra attention to:
    • Makefile: correctness of variable substitution, path handling ($(FRONTEND_DIR)), install_ci flags (--frozen-lockfile) and interactions with SKIP_FRONTEND_BUILD.
    • setup-keycloak.sh: idempotency, API calls for user creation, and secure handling of credentials.
    • docker-compose.yml: validate Keycloak env variable names match the target Keycloak version.
    • frontend/control-plane/package.json: ensure tsc is available in CI/dev environments.

Possibly related PRs

Poem

🐰 I hopped into the Makefile glen,
Centralized runners, then ran again.
Keycloak wakes, a user is born,
Typechecks pass at early morn.
Bun and node — a tidy den!

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 PR title is in Japanese and refers to Keycloak setup script improvements and command additions. However, the raw_summary shows changes to Makefile (dev target), docker-compose.yml configuration, and setup script modifications, which partially aligns with the title but includes broader infrastructure changes than just Keycloak setup improvements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06a9ae9 and 178bb22.

📒 Files selected for processing (3)
  • Makefile (2 hunks)
  • Plan.md (1 hunks)
  • frontend/control-plane/package.json (1 hunks)

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 21, 2025

Copy link
Copy Markdown

コードレビュー完了

PR 52 のレビューが完了しました。

主な評価

✅ 良い点:

  • 冪等性の向上(Realm/Client/User の存在確認)
  • ヘルスチェックの改善(/health/ready エンドポイント使用)
  • デフォルトユーザーの自動作成で開発者体験が向上

⚠️ 改善が必要な点:

  1. セキュリティ(重要): デフォルトユーザーのパスワードが 'password' とハードコードされています(setup-keycloak.sh:158-159)。環境変数化またはランダム生成を推奨します。

  2. エラーハンドリング: Makefile の Keycloak 起動待機ループ(52-59行目)でタイムアウト時のエラーハンドリングがありません。

  3. JSON パース: grep + sed による JSON パースは脆弱です。jq の使用を推奨します。

  4. テストカバレッジ: インフラスクリプトにテストがありません。Bats などの導入を検討してください。

  5. ドキュメント: 新しい make dev コマンドが README.md に記載されていません。

推奨アクション

マージ前に対応すべき項目:

  • ハードコードされたパスワードの修正
  • タイムアウト処理のエラーハンドリング追加

次回以降で対応推奨:

  • jq による安全な JSON パース
  • Bash スクリプトのテスト追加
  • README.md の更新

CI は Green です。セキュリティ上の懸念点を修正後、マージ可能と判断します。

詳細なレビューコメントは上記の通りです。お疲れさまでした!

@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 (3)
Makefile (1)

71-78: DRY principle: Extract duplicated health check loop.

The health check loop is duplicated in both setup-keycloak (lines 52-59) and start-all (lines 71-78) targets. Consider extracting this into a shared helper function or Makefile variable to reduce maintenance burden.

Example refactor using a Makefile variable:

# At top of file after .PHONY declaration
KEYCLOAK_HEALTH_CHECK = bash -c 'for i in {1..30}; do \
	if curl -s -f http://localhost:8080/health/ready > /dev/null 2>&1; then \
		echo "✅ Keycloak が起動しました"; \
		break; \
	fi; \
	echo "   試行 $$i/30..."; \
	sleep 2; \
done'

# Then use in both targets:
@echo "⏳ Keycloak の起動を待っています(最大60秒)..."
@$(KEYCLOAK_HEALTH_CHECK)
infrastructure/docker/keycloak/scripts/setup-keycloak.sh (2)

137-165: Add clarifying comment: default credentials are for local development only.

The hardcoded credentials (username "user", password "password") and admin password defaults are appropriate for local development, but should be documented clearly in the script to prevent accidental use in production contexts.

Add a comment at the top of the user creation section:

 echo ""
 
+# Note: The following credentials are for LOCAL DEVELOPMENT ONLY.
+# Do not use these defaults in production environments.
 # デフォルトユーザーを作成
 echo "👤 デフォルトユーザー 'user' を作成しています..."

Also consider adding a note in the console output to emphasize this:

   echo "✅ ユーザー 'user' (パスワード: password) を作成しました"

becomes:

   echo "✅ ユーザー 'user' (パスワード: password) を作成しました 🔐 (ローカル開発用です)"

139-140: Optional: Use jq for robust JSON parsing instead of grep/sed.

The JSON parsing approach (grep/sed) is fragile and could break if the Keycloak API response format changes. While this maintains consistency with existing code in the script (lines 89-90, 116-117), consider migrating to jq for robustness.

Example refactor:

 USER_ID=$(curl -s "${KEYCLOAK_URL}/admin/realms/${REALM_NAME}/users?username=user" \
-  -H "Authorization: Bearer ${ACCESS_TOKEN}" | grep -o '"id":"[^"]*' | head -1 | sed 's/"id":"//')
+  -H "Authorization: Bearer ${ACCESS_TOKEN}" | jq -r '.[] | select(.username == "user") | .id' 2>/dev/null)

This approach:

  • Handles JSON safely
  • Is more readable
  • Handles edge cases (escaped characters, field ordering)

Note: This would require jq to be installed in the Keycloak container or the script environment. You may want to address all parsing instances together (lines 89-90, 116-117, 139-140) in a future refactoring effort.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01678b4 and 06a9ae9.

📒 Files selected for processing (3)
  • Makefile (1 hunks)
  • infrastructure/docker/keycloak/docker-compose.yml (1 hunks)
  • infrastructure/docker/keycloak/scripts/setup-keycloak.sh (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: claude-review
🔇 Additional comments (4)
Makefile (2)

48-61: Verify health check interval alignment with PR objectives.

The setup-keycloak target implements a 60-second max wait with 2-second intervals (30 iterations × 2s), but the PR objectives state "5秒間隔" (5-second intervals). Please confirm whether the 2-second interval is intentional or should be adjusted to match the documented 5-second intervals.

If 5-second intervals are intended, the loop should be for i in {1..12} (12 iterations × 5s ≈ 60s max):

-	@bash -c 'for i in {1..30}; do \
+	@bash -c 'for i in {1..12}; do \
 		if curl -s -f http://localhost:8080/health/ready > /dev/null 2>&1; then \
 			echo "✅ Keycloak が起動しました"; \
 			break; \
 		fi; \
 		echo "   試行 $$i/30..."; \
-		sleep 2; \
+		sleep 5; \
 	done'

36-37: Original review comment is incorrect; no target shadowing occurs.

In GNU Make, explicit rules defined later override earlier implicit or pattern rules for the same target. The explicit dev: target at lines 36-37 takes precedence over the expansion of $(NPM_RUN_TARGETS): at lines 9-10. When make dev is run, it will correctly execute cd frontend/control-plane && bun run dev, not the root-level bun run dev from the pattern rule. The help text at lines 93, 98, and 203 also confirms this is the intended behavior.

Likely an incorrect or invalid review comment.

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

37-41: Good alignment with Makefile health check requirements.

The addition of KC_HOSTNAME_URL and health/metrics endpoint enables properly supports the improved health check logic in the Makefile. The configuration changes are appropriate for local development.

infrastructure/docker/keycloak/scripts/setup-keycloak.sh (1)

1-20: Idempotency and structure improvements are well-executed.

The addition of user creation logic with existence checks (lines 137-165) follows the same idempotent pattern as the existing realm and client checks. The script properly validates resource existence before creation and logs appropriately.

Also applies to: 167-186

@susumutomita
susumutomita merged commit 5146dfb into main Nov 21, 2025
7 of 8 checks passed
@susumutomita
susumutomita deleted the feat/keycloak-setup-improvements branch November 21, 2025 10:41
@claude

claude Bot commented Nov 21, 2025

Copy link
Copy Markdown

PR Review: Keycloak セットアップスクリプトの改善とコマンド追加

📊 全体評価

このPRは、Keycloakのセットアップスクリプトとビルドフローの両方を改善する内容です。CLAUDE.mdのプレイブックに従い、以下の観点からレビューします。


✅ 良い点

1. 冪等性の向上 🎯

  • Realm/Client/Userの存在チェックを追加し、既に存在する場合はスキップする設計は優れています
  • setup-keycloak.sh の lines 61-83, 87-120, 137-164 で適切に実装されています

2. ヘルスチェックの改善 💊

  • /health/ready エンドポイントを使用した実際のヘルスチェックは、単純な sleep よりも信頼性が高い(line 25)
  • KC_HEALTH_ENABLED: true の追加は適切(docker-compose.yml line 40)

3. Plan.md の記録 📝

  • 問題の発生から解決までのプロセスが詳細に記録されており、CLAUDE.md の要求に準拠

4. 開発者体験の向上 🚀

  • Makefile に SKIP_FRONTEND_BUILD フラグを追加し、環境依存の問題に柔軟に対応

⚠️ 改善提案

1. セキュリティ: デフォルト認証情報の問題 🔐

Critical Security Issue:

デフォルトユーザー(username: user, password: password)がハードコードされています(setup-keycloak.sh lines 137-163)

問題点:

  • 本番環境に誤ってデプロイされた場合、深刻なセキュリティリスクになります
  • パスワードがログに出力されています

推奨対策:

  • 環境変数でパスワードをカスタマイズ可能にする
  • スクリプトに開発環境専用である旨の警告を追加
  • パスワードの直接表示を避ける

2. エラーハンドリングの不足 🚨

問題箇所:

  • setup-keycloak.sh line 50: grep と sed の連鎖でエラーハンドリングが不十分
  • JSON パースに jq を使用していないため、複雑な JSON レスポンスで失敗する可能性があります

推奨修正:

  • jq を使用した堅牢な JSON パース
  • エラー時の詳細なメッセージ出力

3. テストカバレッジの欠如 🧪

問題点:

  • CLAUDE.md では「カバレッジ 100%」を要求していますが、シェルスクリプトのテストがありません
  • Makefile の新しいコマンドにもテストがありません

推奨対策:

  • Bats テストフレームワークを使用した統合テスト
  • CI での冪等性テスト(make setup-keycloak を2回実行)

4. CI 検証の必須化 🔄

現状:

  • PR の説明に CI ステータスの確認が記載されていません
  • CLAUDE.md のプレイブック「CI が Green になるまで次に進まない」に準拠していない可能性があります

推奨アクション:

  • gh pr checks コマンドで CI ステータスを確認
  • PR 本文に CI 通過のチェックボックスを追加

5. ドキュメント不足 📚

不足している情報:

  • SKIP_FRONTEND_BUILD フラグの使用方法がドキュメント化されていない
  • KC_HOSTNAME_URL の変更理由が説明されていない(docker-compose.yml line 37)

推奨追加:

  • QUICKSTART.md または README.md にトラブルシューティングセクションを追加

🎯 コミット前チェックリスト

CLAUDE.md のセルフレビュープロトコルに従い、以下を確認してください:

  • make lint が通過
  • make typecheck が通過
  • make test が通過(該当する場合)
  • make build が通過(または SKIP_FRONTEND_BUILD=1)
  • CI が Green ✅
  • セキュリティ脆弱性がない
  • デバッグコードやコメントアウトがない
  • Plan.md が最新
  • ドキュメントが更新されている

📋 次のステップ

  1. セキュリティ修正を最優先で対応(デフォルトパスワード問題)
  2. CI ステータスを確認し、PR 本文に追記
  3. エラーハンドリングを改善(jq の導入)
  4. テストカバレッジの追加(Bats または CI 統合テスト)
  5. Plan.md に「振り返り (Retrospective)」を記入

🤝 総評

全体として、冪等性とヘルスチェックの改善は優れた設計です。ただし、セキュリティとエラーハンドリングにクリティカルな問題があるため、修正後の再レビューを推奨します。

CLAUDE.md のプレイブック(特にセキュリティとテストカバレッジ)に完全準拠できれば、本番環境に適用可能な品質になります。


参考資料:

  • CLAUDE.md: セキュリティ設計、テスト駆動開発
  • Plan.md: make before-commit フロー修正 セクション

お疲れ様でした!修正後の再レビューをお待ちしています。

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