Skip to content

feat(keys): signing_keys テーブル + key rotation 対応の keymanager 導入#136

Open
anko9801 wants to merge 1 commit into
mainfrom
feat/signing-keys-table
Open

feat(keys): signing_keys テーブル + key rotation 対応の keymanager 導入#136
anko9801 wants to merge 1 commit into
mainfrom
feat/signing-keys-table

Conversation

@anko9801
Copy link
Copy Markdown
Collaborator

@anko9801 anko9801 commented May 5, 2026

概要

JWT 署名鍵を PEM ファイル (`data/private.pem`) から spec 準拠の `signing_keys` テーブルへ移行。複数鍵共存と JWKS でのローテーション公開を可能にする。

背景

仕様の `signing_keys` テーブル定義に対応:

カラム 説明
id UUID PK
kid TEXT UNIQUE, JWK Key ID
algorithm TEXT RS256 / ES256
use_ TEXT sig / enc (`use` は予約語)
status TEXT active / rotated / revoked
public_key TEXT PEM
private_key TEXT PEM
expires_at, rotated_at, created_at TIMESTAMPTZ

ローテーション時は `active → rotated` で JWKS に残し続け、過去発行トークンが検証可能なまま新トークンは新 active 鍵で署名。

変更

スキーマ・クエリ

  • `db/schema.sql`: `signing_keys` テーブル追加 (status / use の CHECK 制約付き)
  • `db/query/oidc.sql`: CRUD + `GetActiveSigningKey`, `ListPublishableSigningKeys`, `MarkSigningKeyRotated`, `RevokeSigningKey`
  • `internal/repository/oidc/*`: sqlc 自動生成

Domain / Repository

  • `internal/domain/signing_key.go`: `SigningKey` 構造体 + status / use enum
  • `internal/repository/signing_key.go`: `SigningKeyRepository` 実装

keymanager パッケージ (新規)

  • `internal/keymanager/manager.go`:
    • `EnsureActiveKey`: 起動時に active 鍵が無ければ自動生成
    • `ActiveKey`: fosite signer 用の現役 private key
    • `PublishableKeys`: JWKS 公開用 (active + rotated)
    • `Rotate`: 既存を rotated に降格して新鍵を active 化

Wiring

  • `cmd/serve.go`: keymanager を構築・初期化、fosite と handler に注入
  • `cmd/oauth.go`: `privateKeyGetter` を keymanager 経由に変更。PEM ファイル系のヘルパー (`loadOrGenerateKey` / `loadKey` / `saveKey`) と未使用の import を削除
  • `cmd/config.go`: 未使用の `oauth.key_file` を削除
  • `internal/router/v1/handler.go`: `OAuthConfig.PrivateKey` を削除し、`KeyProvider` interface 経由で keymanager を受け取る
  • `internal/router/v1/oauth.go`: `GetJWKS` で publishable keys 全件を返却 (回転後も RP は古いトークンを検証可能)
  • `internal/router/v1/client_test.go`: keymanager で active 鍵をプロビジョン
  • `.github/workflows/conformance.yaml`: 不要になった `openssl genpkey` ステップを削除

互換性

  • 既存の kid 計算 (sha256(modulus) の base64url 先頭 8 byte) を踏襲
  • 既存 PEM ファイルは無視される (DB 側で別 kid を生成)

RFC / 仕様根拠

項目 仕様
signing_keys テーブル traPortal v2 仕様
JWK / JWK Set フォーマット RFC 7517 §4, §5
Key Rotation 公開 OIDC Discovery 1.0 §10.1

後続 PR

テスト

  • CI (Lint / Build / Test / Conformance Suite) パス
  • `go build ./...` / `golangci-lint run` 0 issues (確認済み)

…anager

Replaces the on-disk PEM file (data/private.pem) with the spec-aligned
signing_keys table (traPortal v2 §signing_keys). The new keymanager
package owns the lifecycle:

- EnsureActiveKey on startup generates an RSA-2048 / RS256 key when no
  active row exists, otherwise loads and parses the existing one.
- ActiveKey supplies the private half to fosite via the existing
  privateKeyGetter callback, so a Rotate() call is picked up without a
  process restart.
- PublishableKeys returns every active+rotated key so JWKS keeps serving
  previously-issued tokens after a rotation; revoked keys disappear.

The kid scheme is preserved (sha256 over the modulus, base64url) so RPs
continue to see the same kid for the same key material.

Wired through:
- cmd/serve.go: builds the keymanager from the SigningKeyRepository,
  hands it to the fosite provider and the v1 handler.
- cmd/oauth.go: privateKeyGetter resolves the active key at request
  time. loadOrGenerateKey + the PEM file plumbing are removed.
- internal/router/v1/handler.go: introduces a small KeyProvider
  interface so the router does not import fosite/key types directly.
- internal/router/v1/oauth.go: GetJWKS now publishes every publishable
  key.
- internal/router/v1/client_test.go: updated to provision a key via the
  new manager.
- .github/workflows/conformance.yaml: drops the now-dead openssl
  genpkey step (the server creates its own key on first boot).
- cmd/config.go: drops the unused oauth.key_file field.

Refs:
- traPortal v2 仕様 §signing_keys
- RFC 7517 §4 (JWK fields), §5 (JWK Set)
  https://datatracker.ietf.org/doc/html/rfc7517
- OIDC Discovery 1.0 §10.1 (Key Rotation)
  https://openid.net/specs/openid-connect-discovery-1_0.html#RotateSigKeys

Follow-ups:
- Admin endpoint to trigger Rotate() (currently only callable from Go)
- Use kid header on issued tokens via fosite Signer (today fosite picks
  the kid from the JWK set returned by the strategy; the active key is
  always the most recent so verification still works, but explicit kid
  pinning would simplify multi-active scenarios)
- Update PR #134 (RP-Initiated Logout) to verify id_token_hint against
  every publishable key instead of the single old PrivateKey field

Assisted-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@anko9801 anko9801 requested a review from saitenntaisei as a code owner May 5, 2026 10:56
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 5, 2026

Warning

Rate limit exceeded

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

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ 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: CHILL

Plan: Pro

Run ID: f6163a5b-a5c9-4508-9198-b17c7657b099

📥 Commits

Reviewing files that changed from the base of the PR and between 003c323 and 89a9a95.

📒 Files selected for processing (16)
  • .github/workflows/conformance.yaml
  • cmd/config.go
  • cmd/oauth.go
  • cmd/serve.go
  • db/query/oidc.sql
  • db/schema.sql
  • internal/domain/signing_key.go
  • internal/keymanager/manager.go
  • internal/repository/oidc/db.go
  • internal/repository/oidc/models.go
  • internal/repository/oidc/oidc.sql.go
  • internal/repository/oidc/querier.go
  • internal/repository/signing_key.go
  • internal/router/v1/client_test.go
  • internal/router/v1/handler.go
  • internal/router/v1/oauth.go
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/signing-keys-table

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.

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