Skip to content

refactor: policyId 紐づけ方式への移行対応 (GeonicDB #757)#82

Merged
miya0001 merged 12 commits into
mainfrom
refactor/policy-id-migration
Mar 22, 2026
Merged

refactor: policyId 紐づけ方式への移行対応 (GeonicDB #757)#82
miya0001 merged 12 commits into
mainfrom
refactor/policy-id-migration

Conversation

@miya0001

@miya0001 miya0001 commented Mar 21, 2026

Copy link
Copy Markdown
Member

Summary

GeonicDB #757 (認証情報とポリシーの分離 — policyId 紐づけ方式への移行) に対応する CLI 側の変更。

  • API キー (admin api-keys, me api-keys): --scopes, --permissions, --entity-types オプションを削除し、--policy <policyId> オプションを追加
  • OAuth クライアント (admin oauth-clients, me oauth-clients): --scopes オプションと allowedScopes フィールドを削除し、--policy <policyId> オプションを追加。clientNamename にリネーム
  • helpers.ts: SCOPES_HELP_NOTES, API_KEY_SCOPES_HELP_NOTES, VALID_PERMISSIONS, parsePermissions を削除
  • README: フラグ一覧・例文・認可モデルセクションを policyId 方式に更新

Breaking Changes

対象 削除 追加
API キー (admin/me) --scopes, --permissions, --entity-types --policy <policyId>
OAuth クライアント (admin/me) --scopes, allowedScopes --policy <policyId>
OAuth クライアント clientName フィールド name フィールド

Test plan

  • npm run lint — pass
  • npm run typecheck — pass
  • npm test — 628/628 pass
  • E2E テスト (GeonicDB サーバー側の #757 対応が必要)

Closes #80, closes #81

Summary by CodeRabbit

  • 破壊的変更

    • CLIのAPIキー/OAuthクライアントコマンドから --scopes/--permissions/--entity-types を廃止し、代わりに --policy <policyId> を導入
    • OAuthクライアントのフィールド名とCLI例で clientNamename に変更
    • 認可モデルをスコープベースからポリシーベース(policyId)へ移行
  • ドキュメント

    • READMEとCHANGELOGを新しいポリシーベース認可モデルと更新されたCLIフラグ/JSON例に合わせて更新

API キー・OAuth クライアントの認可モデルを policyId 紐づけ方式に移行。

- API キー: --scopes, --permissions, --entity-types を削除し --policy を追加
- OAuth クライアント: --scopes を削除し --policy を追加
- OAuth クライアント: clientName を name にリネーム
- helpers.ts: SCOPES_HELP_NOTES, API_KEY_SCOPES_HELP_NOTES, VALID_PERMISSIONS, parsePermissions を削除

Closes #80, closes #81
- me api-keys create フラグ一覧: --scopes/--permissions/--entity-types を --policy に置換
- admin api-keys フラグ説明: 同上
- me oauth-clients create フラグ説明を追加
- Valid Scopes / Entity Type Restrictions セクションを Authorization Model セクションに統合
- CHANGELOG 更新
@coderabbitai

coderabbitai Bot commented Mar 21, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

スコープ/権限ベースの認可モデルを廃止し、APIキーとOAuthクライアントの認可をXACMLポリシーID(policyId)で紐付ける方式へ移行。CLIフラグとJSONペイロード、関連ドキュメント、テスト、E2Eフックをそれに合わせて更新し、ヘルパーのスコープ/権限ユーティリティを削除。

Changes

Cohort / File(s) Summary
CLI: Admin API キー
src/commands/admin/api-keys.ts
--scopes/--entity-types/--permissionsを削除し、--policy <policyId>を追加。リクエストペイロードをpolicyIdへマッピング、ヘルプ・例を更新。
CLI: Me API キー
src/commands/me-api-keys.ts
上記同様にフラグ削除→--policy追加。parsePermissions等インポート削除。フラグ駆動の入力判定をopts.policy基準へ変更。
CLI: OAuth クライアント
src/commands/admin/oauth-clients.ts, src/commands/me-oauth-clients.ts
JSON例・ヘルプでclientNamenameallowedScopespolicyIdに変更。me側の--scopes--policyへ置換、--save時のスコープ渡しを削除。
ヘルパーの削除
src/helpers.ts
SCOPES_HELP_NOTESAPI_KEY_SCOPES_HELP_NOTESVALID_PERMISSIONSparsePermissions()のエクスポートを削除。
ドキュメント
CHANGELOG.md, README.md
CHANGELOGに破壊的変更を記載。READMEでスコープ/権限/エンティティタイプ記述を削除し、--policy/ポリシー紐づけモデルへ書き換え。例示JSON・CLI例を更新。
テスト: 実装/モックの更新
tests/* (例: tests/admin-api-keys.test.ts, tests/me-api-keys.test.ts, tests/me-oauth-clients.test.ts, tests/setup-command-mocks.ts, tests/helpers.test.ts, 他)
テスト期待値をallowedScopes/permissions/allowedEntityTypesからpolicyIdへ変更。SCOPES_HELP_NOTES/API_KEY_SCOPES_HELP_NOTESのモック削除。parsePermissions関連ユニットテスト削除、一部モック簡素化。
E2E シナリオ
tests/e2e/features/me-oauth-clients.feature, tests/e2e/features/oauth-clients.feature
OAuthクライアント作成の入力をallowedScopesname(JSON)へ変更、CLI例から--scopesを削除。
E2E テストセットアップ
tests/e2e/support/hooks.ts
DBクリーンアップを調整し、users/policies/tenantを保持・スナップショット→復元するロジックを追加。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 分

Poem

🐰 ぽよんぽよん、ポリシー畑で跳ねるよ
フラグをしまって、IDをそっと結ぶ
名前は短く、鍵はしっかりと🔑
テストも元気に、フックは守るよ
ぴょんと進め、新しい認可の道!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main change: migrating to a policyId-based authorization model, replacing scopes/permissions/entity-types with policy attachments across API keys and OAuth clients.
Linked Issues check ✅ Passed All coding requirements from issues #80 and #81 are met: API key commands updated with --policy flag, OAuth clients renamed clientName→name, scopes/permissions/entity-types removed, and helpers refactored accordingly.
Out of Scope Changes check ✅ Passed All changes are directly related to the policyId migration objectives. Documentation, CLI flags, request/response schemas, and test mocks were updated cohesively to reflect the new authorization model.

✏️ 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 refactor/policy-id-migration

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/admin/oauth-clients.ts (1)

55-83: ⚠️ Potential issue | 🟠 Major

admin oauth-clients create の breaking change が CLI に出ていません。

ここは JSON 例だけ policyId に更新されていますが、コマンド自体はまだ --policy を受け付けません。今回の変更説明では admin oauth-clients--policy <policyId> 移行対象として案内されているので、このままだとドキュメント通りの実行が unknown option になります。実装を追加するか、案内を JSON payload の変更だけに絞ってください。

差分案
   const create = oauthClients
     .command("create [json]")
     .description(
       "Create a new OAuth client\n\n" +
         "JSON payload example:\n" +
         "  {\n" +
         '    "name": "my-app",\n' +
         '    "policyId": "<policy-id>"\n' +
         "  }",
     )
+    .option("--name <name>", "Client name")
+    .option("--policy <policyId>", "Policy ID to attach")
     .action(
       withErrorHandler(async (json: unknown, _opts: unknown, cmd: Command) => {
-        const body = await parseJsonInput(json as string | undefined);
+        const opts = cmd.opts() as { name?: string; policy?: string };
+        let body: unknown;
+        if (json) {
+          body = await parseJsonInput(json as string | undefined);
+        } else if (opts.name || opts.policy) {
+          const payload: Record<string, unknown> = {};
+          if (opts.name) payload.name = opts.name;
+          if (opts.policy) payload.policyId = opts.policy;
+          body = payload;
+        } else {
+          body = await parseJsonInput();
+        }
         const client = createClient(cmd);
         const format = getFormat(cmd);
         const response = await client.rawRequest("POST", "/admin/oauth-clients", {
           body,
         });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/admin/oauth-clients.ts` around lines 55 - 83, The CLI example
claims the create command accepts a --policy <policyId> option but the command
defined by the create variable does not parse or forward that flag; add a
commander option to the create command (e.g., .option("--policy <policyId>"))
and update the action to accept opts (or read cmd.opts()) and, if provided,
merge/override body.policyId with the flag value before calling
client.rawRequest; reuse existing helpers (parseJsonInput, createClient,
getFormat, outputResponse, printSuccess) and validate that you don't silently
override an explicit policyId present in the JSON payload (either prefer the
flag or error on conflict).
🧹 Nitpick comments (1)
tests/admin-api-keys.test.ts (1)

323-339: 削除した旧フラグの拒否も 1 本固定しておきたいです。

--policy の正系は確認できていますが、この PR の破壊的変更は --scopes / --permissions / --entity-types を受け付けないことでもあります。今の suite だと古い option 定義が残っても見逃すので、unknown option を確認する回帰テストを 1 本だけでも残しておくと安全です。

Also applies to: 431-449

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/admin-api-keys.test.ts` around lines 323 - 339, Add a regression test
that verifies the CLI rejects the removed/deprecated flags (--scopes,
--permissions, --entity-types) when creating API keys: in the
tests/admin-api-keys.test.ts suite (alongside the existing "includes policyId
when --policy flag is set" test and the related block around lines 431-449) call
runCommand(makeProgram(), ["admin","api-keys","create","--scopes","foo"]) (and
one for --permissions or --entity-types) and assert the command fails with an
"unknown option" error (or that the process exits/non-zero and client.rawRequest
is not called); use the same helpers (makeProgram, runCommand, client.rawRequest
mocks) to locate and implement this single negative test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 11-14: The three Unreleased changelog entries and the Docs line
are missing the PR suffix; update each bullet (the lines starting with
"Breaking: API キー", "Breaking: OAuth クライアント", "Breaking: OAuth クライアントの
`clientName`", and "Docs: README") to append the PR number in the standard
format (e.g., " ( `#82` )" without extra spacing) so they match existing
CHANGELOG.md conventions and the other entries include the PR suffix.

In `@README.md`:
- Around line 198-199: README currently documents `me oauth-clients create`
flags but doesn't call out the breaking rename of JSON field `clientName` →
`name`; update the README to explicitly show the new JSON shape for both `me`
and `admin` examples (e.g. include a JSON snippet or inline note
`{"name":"..."}`), and mention the flag mapping (`--name` now corresponds to the
`name` field) so users know to migrate payloads and config entries from
`clientName` to `name`.

---

Outside diff comments:
In `@src/commands/admin/oauth-clients.ts`:
- Around line 55-83: The CLI example claims the create command accepts a
--policy <policyId> option but the command defined by the create variable does
not parse or forward that flag; add a commander option to the create command
(e.g., .option("--policy <policyId>")) and update the action to accept opts (or
read cmd.opts()) and, if provided, merge/override body.policyId with the flag
value before calling client.rawRequest; reuse existing helpers (parseJsonInput,
createClient, getFormat, outputResponse, printSuccess) and validate that you
don't silently override an explicit policyId present in the JSON payload (either
prefer the flag or error on conflict).

---

Nitpick comments:
In `@tests/admin-api-keys.test.ts`:
- Around line 323-339: Add a regression test that verifies the CLI rejects the
removed/deprecated flags (--scopes, --permissions, --entity-types) when creating
API keys: in the tests/admin-api-keys.test.ts suite (alongside the existing
"includes policyId when --policy flag is set" test and the related block around
lines 431-449) call runCommand(makeProgram(),
["admin","api-keys","create","--scopes","foo"]) (and one for --permissions or
--entity-types) and assert the command fails with an "unknown option" error (or
that the process exits/non-zero and client.rawRequest is not called); use the
same helpers (makeProgram, runCommand, client.rawRequest mocks) to locate and
implement this single negative test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 18210052-5a7b-4978-a02d-f65eea67ae4e

📥 Commits

Reviewing files that changed from the base of the PR and between 3bc1c46 and 3071fca.

📒 Files selected for processing (24)
  • CHANGELOG.md
  • README.md
  • src/commands/admin/api-keys.ts
  • src/commands/admin/oauth-clients.ts
  • src/commands/me-api-keys.ts
  • src/commands/me-oauth-clients.ts
  • src/helpers.ts
  • tests/admin-api-keys.test.ts
  • tests/admin-oauth-clients.test.ts
  • tests/admin-policies.test.ts
  • tests/admin-tenants.test.ts
  • tests/admin-users.test.ts
  • tests/auth.test.ts
  • tests/e2e/features/me-oauth-clients.feature
  • tests/e2e/features/oauth-clients.feature
  • tests/entities.test.ts
  • tests/health.test.ts
  • tests/helpers.test.ts
  • tests/me-api-keys.test.ts
  • tests/me-oauth-clients.test.ts
  • tests/setup-command-mocks.ts
  • tests/snapshots.test.ts
  • tests/temporal.test.ts
  • tests/types.test.ts
💤 Files with no reviewable changes (13)
  • tests/admin-oauth-clients.test.ts
  • tests/snapshots.test.ts
  • tests/temporal.test.ts
  • tests/admin-tenants.test.ts
  • tests/auth.test.ts
  • tests/admin-policies.test.ts
  • tests/entities.test.ts
  • tests/health.test.ts
  • tests/types.test.ts
  • tests/setup-command-mocks.ts
  • src/helpers.ts
  • tests/helpers.test.ts
  • tests/admin-users.test.ts

Comment thread CHANGELOG.md Outdated
Comment thread README.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.

🧹 Nitpick comments (2)
tests/e2e/features/me-oauth-clients.feature (2)

23-29: --policy オプションのテストカバレッジが不足しています。

以前は --scopes read:entities が明示的にテストされていましたが、その代替となる --policy <policyId> オプションのテストシナリオがありません。新しい認可モデルの動作を保証するため、--policy オプションを使用したシナリオを追加することを検討してください。

例:

Scenario: Create an OAuth client with --policy flag
  Given I am logged in
  When I run `geonic me oauth-clients create --name my-policy-bot --policy <testPolicyId>`
  Then the exit code should be 0
  And the output should contain "OAuth client created."
  And stdout should be valid JSON
  And the JSON output should have key "clientId"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/e2e/features/me-oauth-clients.feature` around lines 23 - 29, Add a new
Gherkin scenario mirroring the existing "Create an OAuth client with --name
flag" but using the --policy flag: create a "Scenario: Create an OAuth client
with --policy flag" that runs `geonic me oauth-clients create --name
my-policy-bot --policy <testPolicyId>` (use a fixture or testPolicyId variable)
and include the same assertions as the other scenario (exit code 0, output
contains "OAuth client created.", stdout valid JSON, JSON has key "clientId") so
the new policy-based flow is covered.

31-39: --save フラグとの組み合わせテストも --policy なしのケースのみになっています。

--save オプションと --policy オプションを組み合わせたシナリオ(認証情報の保存と同時にポリシーを指定するケース)のテストも追加すると、より堅牢なテストカバレッジになります。

Also applies to: 57-62

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/e2e/features/me-oauth-clients.feature` around lines 31 - 39, Add an E2E
scenario that tests creating an OAuth client with both --save and --policy flags
together: mirror the existing "Create with --save stores credentials in config"
scenario but run `geonic me oauth-clients create --name my-saved-bot --save
--policy "<policy-name-or-json>"`, assert exit code 0, output contains "OAuth
client created." and "Auto-reauth enabled", and verify the config contains
"clientId", "clientSecret", "token", plus the specified policy is persisted
(check output or config key representing the policy). Apply the same addition
for the analogous scenario around the second instance noted in the comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/e2e/features/me-oauth-clients.feature`:
- Around line 23-29: Add a new Gherkin scenario mirroring the existing "Create
an OAuth client with --name flag" but using the --policy flag: create a
"Scenario: Create an OAuth client with --policy flag" that runs `geonic me
oauth-clients create --name my-policy-bot --policy <testPolicyId>` (use a
fixture or testPolicyId variable) and include the same assertions as the other
scenario (exit code 0, output contains "OAuth client created.", stdout valid
JSON, JSON has key "clientId") so the new policy-based flow is covered.
- Around line 31-39: Add an E2E scenario that tests creating an OAuth client
with both --save and --policy flags together: mirror the existing "Create with
--save stores credentials in config" scenario but run `geonic me oauth-clients
create --name my-saved-bot --save --policy "<policy-name-or-json>"`, assert exit
code 0, output contains "OAuth client created." and "Auto-reauth enabled", and
verify the config contains "clientId", "clientSecret", "token", plus the
specified policy is persisted (check output or config key representing the
policy). Apply the same addition for the analogous scenario around the second
instance noted in the comment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 21986dc7-342d-4897-9f52-5f19dfb57ba2

📥 Commits

Reviewing files that changed from the base of the PR and between a218ff0 and 6177068.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • tests/e2e/features/me-oauth-clients.feature
  • tests/e2e/features/oauth-clients.feature
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/e2e/features/oauth-clients.feature

geonicdb を #757 対応版に更新後、シナリオ間の DB クリーンアップで
デフォルト XACML ポリシーとスーパー管理者ユーザーが削除され
'Access denied by policy' が全テストで発生していた。

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/e2e/support/hooks.ts`:
- Around line 48-52: The current cleanup in the hooks uses preserveCollections
(Set of "users","policies","tenant") and skips dropping them, which leaves their
documents between scenarios; change the logic in the hook that iterates
collections (using mongoClient, db.listCollections(), collections) so that
instead of skipping preserveCollections you call
db.collection(<name>).deleteMany({}) to clear documents for those names (or
restore from a known initial snapshot if available), and continue dropping
non-preserved collections as before; update the loop that checks
c.name.startsWith("system.") and preserveCollections.has(c.name) to perform
deleteMany on preserved names and drop() for others.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 54cb2e81-4c6f-4125-b767-706e862b4818

📥 Commits

Reviewing files that changed from the base of the PR and between 6177068 and 51c0783.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • tests/e2e/support/hooks.ts

Comment thread tests/e2e/support/hooks.ts Outdated
super_admin はデータ API アクセス不可のため、E2E セットアップで
テナント + tenant_admin ユーザーを作成し、データ操作テストは
tenant_admin で実行するよう変更。

- hooks.ts: BeforeAll でテナント・tenant_admin を API 経由で作成
- world.ts: performLogin を tenant_admin に、performSuperAdminLogin を追加
- admin 系 feature: Given I am logged in as super admin に変更
- auth.feature: whoami の期待メールアドレスを tenant_admin に変更
- client.ts: サーバーが不正JWTに403を返すケースでもトークンリフレッシュを発動
- helpers.ts: テナント未割り当て403を認証エラーとして処理
- common.steps.ts: extractId で ruleId を tenantId より優先
- snapshots.feature: clone テストをサーバー仕様に合わせて簡素化

ローカル E2E: 130/130 pass
@miya0001
miya0001 merged commit b9f6da6 into main Mar 22, 2026
7 checks passed
@miya0001
miya0001 deleted the refactor/policy-id-migration branch April 3, 2026 07:39
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.

refactor: policyId 紐づけ方式への移行対応 (#757) refactor: policyId 紐づけ対応 & allowedScopes/permissions 廃止

1 participant