From 4824fa5aee5310c6e43b8c797079261ecaad2f41 Mon Sep 17 00:00:00 2001 From: Paul Yuknewicz Date: Wed, 2 Dec 2026 20:04:20 -0800 Subject: [PATCH 1/3] Handle disabled API built-in keys during APIM migration Never recreate APIM's built-in master subscription as a gateway key. Direct its callers to the existing manual Entra RBAC prerequisite with explicit object IDs and least-privilege model/tool scopes. Reject master targets in older plans and keep caller cutover separate from configuration completion. Deliberately update the golden plan for the changed subscription rationale and caller-RBAC guidance. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/migrate-apim/ARCHITECTURE.md | 20 +++++++ tools/migrate-apim/README.md | 51 ++++++++++++++++-- tools/migrate-apim/capabilities/rules.json | 2 +- tools/migrate-apim/migrate_apim/apply.py | 24 ++++++++- tools/migrate-apim/migrate_apim/plan.py | 53 ++++++++++++++++--- tools/migrate-apim/schemas/plan.schema.json | 2 +- .../migrate-apim/tests/golden/decisions.json | 15 ++++-- tools/migrate-apim/tests/test_apply.py | 49 +++++++++++++++++ tools/migrate-apim/tests/test_plan.py | 45 ++++++++++++++-- 9 files changed, 240 insertions(+), 21 deletions(-) diff --git a/tools/migrate-apim/ARCHITECTURE.md b/tools/migrate-apim/ARCHITECTURE.md index 6ee9e698..03812ddc 100644 --- a/tools/migrate-apim/ARCHITECTURE.md +++ b/tools/migrate-apim/ARCHITECTURE.md @@ -119,6 +119,26 @@ What one released wheel actually offers: every `az aigateway` command and the op The catalog says what the tool intends to call; the snapshot says what exists. `compile` compares them. +## Subscription keys and caller identity + +The planner never turns APIM's built-in master subscription into a gateway API key. +It recognizes the source resource name or subscription ID, not the display name or +service-wide scope. The same check rejects master targets in older plans during +preflight and in the key command builder, so migration cannot recreate the global +all-access key when API built-in keys are disabled. The explicit per-consumer-key +option still creates fresh keys for ordinary subscriptions. + +`prereq:caller-rbac` is the manual identity cutover boundary. An operator must supply +each caller's Entra object ID, principal type, and least-privilege model/alias or +tool-server scopes, then assign runtime roles and verify the callers using tokens. +APIM's shared master credential cannot identify its consumers. No catalog capability +is claimed for automatic identity discovery or caller role-assignment apply. + +Configuration phases and caller cutover remain separate. A master-only inventory +produces no key targets, so the keys phase completes normally without a skip or +journal override. It does not acknowledge the caller prerequisite or prove runtime +access. Callers without an identity mapping remain on APIM until that work is done. + ## The Version Contract When the Azure CLI extension gains a new capability: diff --git a/tools/migrate-apim/README.md b/tools/migrate-apim/README.md index 0612176c..b139ab5d 100644 --- a/tools/migrate-apim/README.md +++ b/tools/migrate-apim/README.md @@ -1090,10 +1090,53 @@ one, and nothing else: it stopped doubling as the destination's carrier, because a logger and no such policy had nothing to settle at all, and two carriers for one fact is how they drift apart. -**`keys` creates nothing unless asked.** `entra-rbac` — the proposal — creates no key at all, and -only `gateway-key-per-consumer` shapes one gateway key per APIM subscription, carrying the name and -not the value. No APIM key crosses: the service will not hand it over and the gateway will not take -one, so every caller is re-keyed from `api-key list-secrets`, which only the operator runs. +**`keys` never recreates APIM's built-in `master` subscription.** The intent is to handle API +built-in keys being disabled without creating a replacement global all-access key. `entra-rbac`, +the proposal, creates no keys. `gateway-key-per-consumer` creates fresh gateway-wide keys for +ordinary APIM subscriptions only, carrying their names, not their values. An ordinary subscription +is not treated as master just because its display name says "All access" or its scope covers all +APIs. Callers using those replacement keys must be re-keyed separately; only the operator runs +`api-key list-secrets`. Older plans that still target master fail preflight and must be regenerated, +not edited to bypass the check. + +**Master's callers move to identities, not another shared key.** The shared source credential +cannot identify its consumers. For each caller that will use Entra, including every master caller +leaving APIM, supply its Entra object ID (not application/client ID), principal type, and the full +resource IDs of the models, aliases, or MCP servers it needs. `prereq:caller-rbac` gives the role +commands; apply does not discover these identities or create their role assignments. Use `User`, +`Group`, or `ServicePrincipal` as the principal type, including `ServicePrincipal` for managed +identities. Grant only the required assets, not gateway-wide access by default: + +```bash +# Inspect the access decision, settle it on entra-rbac, then regenerate the plan. +migrate-apim summary plan.json --item access/subscriptions +migrate-apim plan --inventory inventory.json -o plan.json +migrate-apim apply --plan plan.json --inventory inventory.json --preflight + +# After the target assets exist, repeat only the applicable grants for each caller. +az role assignment create --role 'AI Gateway Models User' \ + --assignee-object-id --assignee-principal-type \ + --scope +az role assignment create --role 'AI Gateway Tools User' \ + --assignee-object-id --assignee-principal-type \ + --scope + +# Record this only after changing the callers to Entra tokens and verifying runtime access. +migrate-apim apply --plan plan.json --inventory inventory.json \ + --acknowledge prereq:caller-rbac +``` + +An alias scope is `/workspaces/default/aliases/`; an MCP scope is +`/workspaces/default/toolServers/`. Check both an allowed call +and a call outside the assigned scope using the caller's own identity. See +[caller authentication](https://ai.gateway.azure.com/docs/security/authenticate-entra) for tokens +and supported identities. If caller identities are not yet known, keep those callers on APIM. +Do not recreate master, turn built-in keys on, or skip a phase as a workaround. + +**Configuration completion is not caller cutover.** Run each configuration phase normally, +including an empty `keys` phase. Master exclusion does not leave a phase blocked and does not +acknowledge `prereq:caller-rbac`. The closing report continues to list that prerequisite until +the operator records it; acknowledgement is an operator claim, not a runtime test by this tool. **`--preflight` also asks for a list to be kept**, once, under the phases it just printed: one entry per phase, ticked from what a run prints. A migration runs one phase per invocation over as many diff --git a/tools/migrate-apim/capabilities/rules.json b/tools/migrate-apim/capabilities/rules.json index e651c725..ff948a91 100644 --- a/tools/migrate-apim/capabilities/rules.json +++ b/tools/migrate-apim/capabilities/rules.json @@ -676,7 +676,7 @@ "answer": "choose", "options": ["gateway-key-per-consumer", "entra-rbac", "retain-in-apim"], "proposal": "entra-rbac", - "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. AI Gateway keys are gateway-wide and no key value can be imported, so every caller is re-keyed." + "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. Prefer Entra RBAC with caller object IDs and least-privilege model/tool scopes supplied through prereq:caller-rbac. APIM's built-in master (all-access) subscription is never recreated as an API key, so migration does not undo disabled API built-in keys. gateway-key-per-consumer creates fresh gateway-wide keys for ordinary subscriptions only; no key value is imported." }, { "id": "structural/certificates", diff --git a/tools/migrate-apim/migrate_apim/apply.py b/tools/migrate-apim/migrate_apim/apply.py index fa263360..89af543e 100644 --- a/tools/migrate-apim/migrate_apim/apply.py +++ b/tools/migrate-apim/migrate_apim/apply.py @@ -40,7 +40,7 @@ # for "resolved on the way out" and every one of them must have a resolver; # `$fromExport` had none for several releases, and a marker and its resolver # spelled in two places is how that stayed invisible. -from .plan import OPENAPI_MARKER +from .plan import OPENAPI_MARKER, is_master_subscription from .resolve import ResolveError, resolve_secret SCHEMA_VERSION = "1.0" @@ -259,6 +259,17 @@ def finding(code: str, blocking: bool, message: str, remedy: str = "") -> None: "Re-apply them to the items that replaced them, or confirm they are not needed.", ) + if any(_is_master_key(obj) + for step in steps_for(plan) if step.capability_id == "key.create" + for obj in step.objects): + finding( + "masterKey", True, + "The plan would recreate APIM's built-in master subscription as a gateway API key.", + "Re-run plan to remove master key targets. Supply caller object IDs and " + "least-privilege asset scopes through prereq:caller-rbac; do not enable API built-in " + "keys or skip a configuration phase to work around this.", + ) + # A secret that cannot be retrieved mechanically stops a step mid-phase. secrets_by_id = {entry["id"]: entry for entry in inventory.get("secrets") or []} needed = _needed_secret_refs(plan) @@ -1487,6 +1498,12 @@ def command(verb: str, *flags: str) -> tuple[list[str], list[str]]: raise ApplyError(f"no gateway-wide mapping for a {kind!r} policy") +def _is_master_key(obj: dict[str, Any]) -> bool: + return is_master_subscription(obj) or is_master_subscription({ + "id": (obj.get("replaces") or {}).get("subscriptionId"), + }) + + def _api_key_create(executor: Executor, step: Step, obj: dict[str, Any]) -> tuple[list[str], list[str]]: """A gateway data-plane key. @@ -1496,6 +1513,11 @@ def _api_key_create(executor: Executor, step: Step, obj: dict[str, Any]) -> tupl """ if not obj.get("name"): raise ApplyError("the plan supplies no name for this key") + if _is_master_key(obj): + raise ApplyError( + "APIM's built-in master subscription must not become a gateway API key. " + "Re-run plan and complete prereq:caller-rbac for its callers." + ) argv = [ "az", "aigateway", "api-key", "create", *executor.target.selectors, "--gateway-name", executor.target.name, "-n", obj["name"], diff --git a/tools/migrate-apim/migrate_apim/plan.py b/tools/migrate-apim/migrate_apim/plan.py index a71335b5..dcb7e585 100644 --- a/tools/migrate-apim/migrate_apim/plan.py +++ b/tools/migrate-apim/migrate_apim/plan.py @@ -1895,7 +1895,7 @@ def _structural(self) -> None: # staying in APIM, this item is a decision with nothing to build, # and objects shaped for it would be keys nobody asked for. target=( - {"capability": "key.create", "objects": _key_objects(subscriptions)} + _objects_or_none("key.create", _key_objects(subscriptions)) if self._settled_value(ids.item("access", "subscriptions")) == "gateway-key-per-consumer" else {} ), @@ -2278,14 +2278,43 @@ def _manual_prerequisites(self) -> None: { "command": ( "az role assignment create --role 'AI Gateway Models User' " - "--assignee --scope " + "--assignee-object-id " + "--assignee-principal-type " + "--scope " ), "roleDefinitionId": "a6b68e3d-a1f0-4c60-8678-237c050cf4ea", - "note": "Use 'AI Gateway Tools User' for MCP callers, or 'AI Gateway User' for both.", + "note": ( + "Use the caller's Entra object ID, not its application/client ID. " + "principal-type is User, Group, or ServicePrincipal (including managed " + "identities). Repeat only for the models or aliases this caller needs." + ), + }, + { + "command": ( + "az role assignment create --role 'AI Gateway Tools User' " + "--assignee-object-id " + "--assignee-principal-type " + "--scope " + ), + "roleDefinitionId": "dce03f8d-857f-4e40-a90d-67770fa6ecd2", + "note": "Repeat only for the MCP tool servers this caller needs.", }, ], - "summary": "Assign callers AI Gateway Models User / Tools User at the right scope", - "detail": "A management role such as Contributor does not imply runtime invocation access.", + "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC", + "detail": ( + "APIM's built-in master (all-access) subscription is never recreated as an API " + "key, including when API built-in keys are disabled on the target. Its shared " + "credential cannot identify its consumers, so automatic identity conversion is " + "not possible. Before caller cutover, supply each caller's Entra object ID, " + "principal type, and required model/alias or tool-server resource IDs. Assign " + "only those runtime roles and scopes, change the callers to Entra tokens, and " + "verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. " + "If identities cannot be supplied yet, keep those callers on APIM; do not " + "recreate master or enable built-in keys as a workaround. A management role " + "such as Contributor does not imply runtime invocation access. Configuration " + "phases can complete before this prerequisite is acknowledged; their completion " + "does not establish caller cutover." + ), }) if assets.get("mcpServers"): if any( @@ -3385,8 +3414,18 @@ def _cidr_cover(start: Any, end: Any) -> list[str]: return [] +def is_master_subscription(entry: dict[str, Any]) -> bool: + """Identify APIM's built-in subscription, not a user-selected display name.""" + identifier = (entry.get("id") or "").rstrip("/").casefold() + return ( + (entry.get("name") or "").casefold() == "master" + or identifier == "subscription:master" + or identifier.endswith("/subscriptions/master") + ) + + def _key_objects(subscriptions: list[dict[str, Any]]) -> list[dict[str, Any]]: - """One gateway key per APIM subscription that was carrying callers. + """One gateway key per ordinary APIM subscription that was carrying callers. The key *value* never crosses: APIM will not hand it over and the gateway will not take one. So these are new keys with the old names, and every @@ -3394,6 +3433,8 @@ def _key_objects(subscriptions: list[dict[str, Any]]) -> list[dict[str, Any]]: """ objects = [] for entry in subscriptions: + if is_master_subscription(entry): + continue name = _slug(entry.get("name") or "") if not name: continue diff --git a/tools/migrate-apim/schemas/plan.schema.json b/tools/migrate-apim/schemas/plan.schema.json index 1062b2b3..3b50d636 100644 --- a/tools/migrate-apim/schemas/plan.schema.json +++ b/tools/migrate-apim/schemas/plan.schema.json @@ -117,7 +117,7 @@ }, "prerequisites": { - "description": "Steps the tool cannot perform, surfaced before anything is executed.", + "description": "Steps the tool cannot perform, surfaced before anything is executed. prereq:caller-rbac requires operator-supplied caller Entra object IDs, principal types, and least-privilege model/alias or tool-server scopes, including for APIM master callers whose shared key cannot identify them. Configuration completion does not establish caller cutover; acknowledgement records the operator's claim, not an automatic conversion or runtime check.", "type": "array", "items": { "type": "object", diff --git a/tools/migrate-apim/tests/golden/decisions.json b/tools/migrate-apim/tests/golden/decisions.json index 73d59acd..297fe7c8 100644 --- a/tools/migrate-apim/tests/golden/decisions.json +++ b/tools/migrate-apim/tests/golden/decisions.json @@ -2146,7 +2146,7 @@ } ], "proposal": "entra-rbac", - "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. AI Gateway keys are gateway-wide and no key value can be imported, so every caller is re-keyed.", + "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. Prefer Entra RBAC with caller object IDs and least-privilege model/tool scopes supplied through prereq:caller-rbac. APIM's built-in master (all-access) subscription is never recreated as an API key, so migration does not undo disabled API built-in keys. gateway-key-per-consumer creates fresh gateway-wide keys for ordinary subscriptions only; no key value is imported.", "shapeDigest": "sha256:8f827c3aa469742d9e2aaba848f579dae5aa9daa81cb9de7c5f9d2fe6990b31d", "source": { "aspect": "subscriptions", @@ -2322,15 +2322,20 @@ { "commands": [ { - "command": "az role assignment create --role 'AI Gateway Models User' --assignee --scope ", - "note": "Use 'AI Gateway Tools User' for MCP callers, or 'AI Gateway User' for both.", + "command": "az role assignment create --role 'AI Gateway Models User' --assignee-object-id --assignee-principal-type --scope ", + "note": "Use the caller's Entra object ID, not its application/client ID. principal-type is User, Group, or ServicePrincipal (including managed identities). Repeat only for the models or aliases this caller needs.", "roleDefinitionId": "a6b68e3d-a1f0-4c60-8678-237c050cf4ea" + }, + { + "command": "az role assignment create --role 'AI Gateway Tools User' --assignee-object-id --assignee-principal-type --scope ", + "note": "Repeat only for the MCP tool servers this caller needs.", + "roleDefinitionId": "dce03f8d-857f-4e40-a90d-67770fa6ecd2" } ], - "detail": "A management role such as Contributor does not imply runtime invocation access.", + "detail": "APIM's built-in master (all-access) subscription is never recreated as an API key, including when API built-in keys are disabled on the target. Its shared credential cannot identify its consumers, so automatic identity conversion is not possible. Before caller cutover, supply each caller's Entra object ID, principal type, and required model/alias or tool-server resource IDs. Assign only those runtime roles and scopes, change the callers to Entra tokens, and verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. If identities cannot be supplied yet, keep those callers on APIM; do not recreate master or enable built-in keys as a workaround. A management role such as Contributor does not imply runtime invocation access. Configuration phases can complete before this prerequisite is acknowledged; their completion does not establish caller cutover.", "id": "prereq:caller-rbac", "owner": "azure-administrator", - "summary": "Assign callers AI Gateway Models User / Tools User at the right scope" + "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC" }, { "detail": "Several CLI commands dispatch by name without --ids, and in a migration the source APIM and the target gateway plausibly share a name.", diff --git a/tools/migrate-apim/tests/test_apply.py b/tools/migrate-apim/tests/test_apply.py index 400eb644..1bb873c5 100644 --- a/tools/migrate-apim/tests/test_apply.py +++ b/tools/migrate-apim/tests/test_apply.py @@ -165,6 +165,20 @@ def test_manual_prerequisites_are_raised_but_do_not_block(self, inventory, settl notes = [f for f in preflight(settled, inventory) if not f["blocking"]] assert any(f["code"] == "prerequisites" for f in notes) + @pytest.mark.parametrize("obj", [ + {"name": "master"}, + {"name": "MASTER"}, + {"name": "renamed", "replaces": {"subscriptionId": "subscription:master"}}, + {"name": "renamed", "replaces": {"subscriptionId": f"{SERVICE}/subscriptions/master"}}, + ]) + def test_old_plans_cannot_recreate_master(self, inventory, settled, obj): + item = next(i for i in settled["items"] if i["capabilityId"] == "key.create") + item["target"] = {"capability": "key.create", "objects": [obj]} + findings = [f for f in preflight(settled, inventory) if f["blocking"]] + assert any(f["code"] == "masterKey" for f in findings) + assert "prereq:caller-rbac" in next(f["remedy"] for f in findings + if f["code"] == "masterKey") + def test_a_same_named_legacy_service_blocks(self, inventory, settled): def runner(argv, _payload=None): return CommandResult(0, json.dumps({"id": "/x", "type": "Microsoft.ApiManagement/service"})) @@ -181,6 +195,32 @@ def test_an_unretrievable_credential_blocks(self, inventory, settled): class TestPhases: + @pytest.mark.parametrize("decision", ["entra-rbac", "gateway-key-per-consumer"]) + def test_master_only_keys_phase_completes_without_claiming_caller_cutover( + self, inventory, settled, decision + ): + source = copy.deepcopy(inventory) + source["apim"]["subscriptions"] = [ + s for s in source["apim"]["subscriptions"] if s["name"] == "master" + ] + item = next(i for i in settled["items"] if i["capabilityId"] == "key.create") + item["decision"] = decision + plan = build_plan(source, CapabilityMap.load(), previous=settled) + next(i for i in plan["items"] if i["capabilityId"] == "key.create")["status"] = "adapted" + runner = _Runner() + journal = new_journal(plan) + executor = Executor(plan, source, journal, runner=runner) + assert executor.run_phase("keys") == [] + executor = Executor(plan, source, journal, runner=runner, execute=True) + assert executor.run_phase("keys") == [] + assert executor.phase_complete("keys") + assert journal["phases"]["keys"]["status"] == "complete" + assert not runner.calls + assert "prereq:caller-rbac" not in journal["acknowledged"] + closing = "\n".join(summary.render_verify(journal, plan)) + assert "prereq:caller-rbac" in closing + assert "does not serve traffic" in closing + def test_steps_come_out_in_dependency_order(self, settled): phases = [step.phase for step in steps_for(settled)] assert phases == sorted(phases, key=PHASES.index) @@ -1494,6 +1534,15 @@ def test_a_key_is_created_by_name_and_never_carries_a_value(self, settled, inven # across would be a value this tool invented. assert not any(flag in argv for flag in ("--value", "--primary-key", "--secondary-key")) + @pytest.mark.parametrize("obj", [ + {"name": "master"}, + {"name": "MASTER"}, + {"name": "renamed", "replaces": {"subscriptionId": "subscription:master"}}, + ]) + def test_master_is_refused_even_without_preflight(self, settled, inventory, obj): + with pytest.raises(ApplyError, match="prereq:caller-rbac"): + self._build(settled, inventory, "key.create", obj) + def test_a_telemetry_exporter_sends_its_destination_through_a_file(self, settled, inventory): argv = self._build(settled, inventory, "telemetry.create", {"name": "appinsights", "kind": "ApplicationInsights", diff --git a/tools/migrate-apim/tests/test_plan.py b/tools/migrate-apim/tests/test_plan.py index 20fd541b..dd9b5422 100644 --- a/tools/migrate-apim/tests/test_plan.py +++ b/tools/migrate-apim/tests/test_plan.py @@ -1763,7 +1763,7 @@ def test_entra_rbac_creates_no_keys(self, plan): assert item["proposal"] == "entra-rbac" assert not (item.get("target") or {}).get("objects") - def test_a_key_per_consumer_shapes_one_key_per_subscription(self, inventory, capabilities): + def test_a_key_per_consumer_excludes_the_builtin_master(self, inventory, capabilities): import copy first = build_plan(copy.deepcopy(inventory), capabilities) @@ -1772,16 +1772,55 @@ def test_a_key_per_consumer_shapes_one_key_per_subscription(self, inventory, cap if item["id"] == item_id: item["status"] = "adapted" item["decision"] = "gateway-key-per-consumer" + item["target"] = { + "capability": "key.create", + "objects": [{"name": "team-a"}, {"name": "master"}], + } second = build_plan(copy.deepcopy(inventory), capabilities, previous=first) item = next(i for i in second["items"] if i["id"] == item_id) objects = (item["target"] or {})["objects"] - subscriptions = inventory["apim"]["subscriptions"] - assert len(objects) == len(subscriptions) + assert [obj["name"] for obj in objects] == ["team-a"] for obj in objects: # The value is the one thing that cannot come across. assert obj["replaces"]["valueCarriedOver"] is False assert "value" not in obj and "primaryKey" not in obj + @pytest.mark.parametrize("name", ["master", "MASTER", "renamed-master"]) + def test_master_is_identified_by_resource_name_or_id(self, inventory, name): + source = copy.deepcopy(inventory) + master = next(s for s in source["apim"]["subscriptions"] if s["name"] == "master") + master["name"] = name + master["id"] = master["id"].upper() + assert [obj["name"] for obj in plan_mod._key_objects( + source["apim"]["subscriptions"] + )] == ["team-a"] + + def test_an_ordinary_all_api_subscription_is_not_master(self): + subscription = { + "id": f"{SERVICE}/subscriptions/app", + "name": "app", + "displayName": "All access", + "scope": {"level": "service"}, + } + assert [obj["name"] for obj in plan_mod._key_objects([subscription])] == ["app"] + + def test_caller_rbac_requires_explicit_identities_and_asset_scopes(self, plan): + prereq = next(p for p in plan["prerequisites"] if p["id"] == "prereq:caller-rbac") + commands = prereq["commands"] + assert len(commands) == 2 + for command in commands: + assert "--assignee-object-id " in command["command"] + assert "--assignee-principal-type " in command["command"] + assert "" not in command["command"] + assert "AI Gateway Models User" in commands[0]["command"] + assert "--scope " in commands[0]["command"] + assert "AI Gateway Tools User" in commands[1]["command"] + assert "--scope " in commands[1]["command"] + assert "master" in prereq["detail"] + assert "cannot identify" in prereq["detail"] + assert "before acknowledging" in prereq["detail"] + assert "configuration" in prereq["detail"].lower() + class TestAttributesWithNoTargetField: def test_they_are_recorded_on_the_object_rather_than_dropped(self, inventory, capabilities): From aea75a6f9ccf9c9756c5f8db7b075458a351443e Mon Sep 17 00:00:00 2001 From: Paul Yuknewicz Date: Wed, 2 Dec 2026 21:12:49 -0800 Subject: [PATCH 2/3] Make Entra identity the normative migration default List Entra RBAC first with explicit no-key behavior. Describe per-consumer keys only as an opt-in for non-Entra clients. Lead caller prerequisites and documentation with identities and least-privilege model/tool scopes, while retaining normal phase completion and master-key guards. Deliberately update the golden plan for the normative access choices and prerequisite wording. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/migrate-apim/ARCHITECTURE.md | 27 ++++++---- tools/migrate-apim/README.md | 50 +++++++++++-------- tools/migrate-apim/capabilities/rules.json | 17 ++++++- tools/migrate-apim/migrate_apim/plan.py | 12 ++--- tools/migrate-apim/schemas/plan.schema.json | 2 +- .../migrate-apim/tests/golden/decisions.json | 14 +++--- tools/migrate-apim/tests/test_plan.py | 33 ++++++++++-- 7 files changed, 105 insertions(+), 50 deletions(-) diff --git a/tools/migrate-apim/ARCHITECTURE.md b/tools/migrate-apim/ARCHITECTURE.md index 03812ddc..66e6abcf 100644 --- a/tools/migrate-apim/ARCHITECTURE.md +++ b/tools/migrate-apim/ARCHITECTURE.md @@ -121,23 +121,28 @@ The catalog says what the tool intends to call; the snapshot says what exists. ` ## Subscription keys and caller identity -The planner never turns APIM's built-in master subscription into a gateway API key. -It recognizes the source resource name or subscription ID, not the display name or -service-wide scope. The same check rejects master targets in older plans during -preflight and in the key command builder, so migration cannot recreate the global -all-access key when API built-in keys are disabled. The explicit per-consumer-key -option still creates fresh keys for ordinary subscriptions. +Microsoft Entra ID is the default authentication for runtime callers. The planner +proposes `entra-rbac` first, explains that it creates no API keys, and produces no +key targets when the operator accepts it. This path works with API built-in keys +disabled. `prereq:caller-rbac` is the manual identity cutover boundary. An operator must supply each caller's Entra object ID, principal type, and least-privilege model/alias or tool-server scopes, then assign runtime roles and verify the callers using tokens. -APIM's shared master credential cannot identify its consumers. No catalog capability +APIM's shared credentials cannot identify their consumers. No catalog capability is claimed for automatic identity discovery or caller role-assignment apply. -Configuration phases and caller cutover remain separate. A master-only inventory -produces no key targets, so the keys phase completes normally without a skip or -journal override. It does not acknowledge the caller prerequisite or prove runtime -access. Callers without an identity mapping remain on APIM until that work is done. +Configuration phases and caller cutover remain separate. Run every phase in order, +including the empty keys phase on the default path, without a skip or journal +override. Configuration completion does not acknowledge the caller prerequisite or +prove runtime access. Callers without an identity mapping remain on APIM until that +work is done. + +`gateway-key-per-consumer` is an explicit opt-in for non-Entra clients only. It +creates fresh gateway-wide keys for ordinary subscriptions, never APIM's built-in +master subscription. The planner recognizes master by source resource name or +subscription ID, not display name or service-wide scope. Preflight and the key +command builder reject master targets in older plans as well. ## The Version Contract diff --git a/tools/migrate-apim/README.md b/tools/migrate-apim/README.md index b139ab5d..eaf48c8a 100644 --- a/tools/migrate-apim/README.md +++ b/tools/migrate-apim/README.md @@ -1090,29 +1090,28 @@ one, and nothing else: it stopped doubling as the destination's carrier, because a logger and no such policy had nothing to settle at all, and two carriers for one fact is how they drift apart. -**`keys` never recreates APIM's built-in `master` subscription.** The intent is to handle API -built-in keys being disabled without creating a replacement global all-access key. `entra-rbac`, -the proposal, creates no keys. `gateway-key-per-consumer` creates fresh gateway-wide keys for -ordinary APIM subscriptions only, carrying their names, not their values. An ordinary subscription -is not treated as master just because its display name says "All access" or its scope covers all -APIs. Callers using those replacement keys must be re-keyed separately; only the operator runs -`api-key list-secrets`. Older plans that still target master fail preflight and must be regenerated, -not edited to bypass the check. - -**Master's callers move to identities, not another shared key.** The shared source credential -cannot identify its consumers. For each caller that will use Entra, including every master caller -leaving APIM, supply its Entra object ID (not application/client ID), principal type, and the full -resource IDs of the models, aliases, or MCP servers it needs. `prereq:caller-rbac` gives the role -commands; apply does not discover these identities or create their role assignments. Use `User`, -`Group`, or `ServicePrincipal` as the principal type, including `ServicePrincipal` for managed -identities. Grant only the required assets, not gateway-wide access by default: +**Use Microsoft Entra ID for runtime callers.** The default migration creates no API keys. +Accept `entra-rbac`, grant each caller the runtime roles it needs on specific models, aliases, or +MCP servers, and switch the caller to Entra tokens. This is the expected path with API built-in +keys disabled. + +Supply each caller's Entra object ID (not application/client ID), principal type, and the full +resource IDs of its required assets. `prereq:caller-rbac` gives the role commands; apply does not +discover identities or create caller role assignments. Shared source credentials cannot identify +their consumers, so the operator supplies that mapping. Use `User`, `Group`, or `ServicePrincipal` +as the principal type, including `ServicePrincipal` for managed identities. Grant only the required +assets, not gateway-wide access: ```bash -# Inspect the access decision, settle it on entra-rbac, then regenerate the plan. +# Accept the entra-rbac proposal on the access decision, then regenerate the plan. migrate-apim summary plan.json --item access/subscriptions migrate-apim plan --inventory inventory.json -o plan.json migrate-apim apply --plan plan.json --inventory inventory.json --preflight +# Repeat this rehearsal/execute pair for every configuration phase, in order. +migrate-apim apply --plan plan.json --inventory inventory.json --next-phase +migrate-apim apply --plan plan.json --inventory inventory.json --next-phase --execute + # After the target assets exist, repeat only the applicable grants for each caller. az role assignment create --role 'AI Gateway Models User' \ --assignee-object-id --assignee-principal-type \ @@ -1131,13 +1130,24 @@ An alias scope is `/workspaces/default/aliases/ and a call outside the assigned scope using the caller's own identity. See [caller authentication](https://ai.gateway.azure.com/docs/security/authenticate-entra) for tokens and supported identities. If caller identities are not yet known, keep those callers on APIM. -Do not recreate master, turn built-in keys on, or skip a phase as a workaround. +Do not turn built-in keys on or skip a phase as a workaround. **Configuration completion is not caller cutover.** Run each configuration phase normally, -including an empty `keys` phase. Master exclusion does not leave a phase blocked and does not -acknowledge `prereq:caller-rbac`. The closing report continues to list that prerequisite until +including the empty `keys` phase on the default path. No phase needs a skip or journal override. +Configuration completion does not acknowledge `prereq:caller-rbac`. The closing report lists it until the operator records it; acknowledgement is an operator claim, not a runtime test by this tool. +**Explicit opt-in: keys for non-Entra clients.** Choose `gateway-key-per-consumer` only for clients +that cannot use Entra. This option creates fresh gateway-wide keys for ordinary APIM subscriptions, +carrying their names, not their values. +Distribute the replacement credentials and change those clients separately; only the operator +runs `api-key list-secrets`. + +APIM's built-in `master` subscription is never recreated. An ordinary subscription is not treated +as master just because its display name says "All access" or its scope covers all APIs. Older +plans that still target master fail preflight and must be regenerated, not edited to bypass the +check. Do not recreate a global all-access key or enable built-in keys to work around that guard. + **`--preflight` also asks for a list to be kept**, once, under the phases it just printed: one entry per phase, ticked from what a run prints. A migration runs one phase per invocation over as many turns, so the thing holding it together is a list outside the tool — and an agent told to keep one diff --git a/tools/migrate-apim/capabilities/rules.json b/tools/migrate-apim/capabilities/rules.json index ff948a91..80d51b19 100644 --- a/tools/migrate-apim/capabilities/rules.json +++ b/tools/migrate-apim/capabilities/rules.json @@ -674,9 +674,22 @@ "selects": "apim.subscriptions", "verdict": "partial", "answer": "choose", - "options": ["gateway-key-per-consumer", "entra-rbac", "retain-in-apim"], + "options": [ + { + "value": "entra-rbac", + "consequence": "Default: use Microsoft Entra ID for runtime callers with least-privilege model/tool roles and scopes. Creates no keys; complete prereq:caller-rbac for caller cutover." + }, + { + "value": "gateway-key-per-consumer", + "consequence": "Explicit opt-in for non-Entra clients only. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master; distribute the new credentials to those clients separately. No APIM key value is imported." + }, + { + "value": "retain-in-apim", + "consequence": "Keep callers on APIM until they are ready for identity cutover." + } + ], "proposal": "entra-rbac", - "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. Prefer Entra RBAC with caller object IDs and least-privilege model/tool scopes supplied through prereq:caller-rbac. APIM's built-in master (all-access) subscription is never recreated as an API key, so migration does not undo disabled API built-in keys. gateway-key-per-consumer creates fresh gateway-wide keys for ordinary subscriptions only; no key value is imported." + "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access." }, { "id": "structural/certificates", diff --git a/tools/migrate-apim/migrate_apim/plan.py b/tools/migrate-apim/migrate_apim/plan.py index dcb7e585..312529f7 100644 --- a/tools/migrate-apim/migrate_apim/plan.py +++ b/tools/migrate-apim/migrate_apim/plan.py @@ -2302,15 +2302,15 @@ def _manual_prerequisites(self) -> None: ], "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC", "detail": ( - "APIM's built-in master (all-access) subscription is never recreated as an API " - "key, including when API built-in keys are disabled on the target. Its shared " - "credential cannot identify its consumers, so automatic identity conversion is " - "not possible. Before caller cutover, supply each caller's Entra object ID, " - "principal type, and required model/alias or tool-server resource IDs. Assign " + "Use Microsoft Entra ID for runtime callers. The default migration creates no " + "API keys and works with API built-in keys disabled. Before caller cutover, " + "supply each caller's Entra object ID, principal type, and required model/alias " + "or tool-server resource IDs. APIM's shared credentials cannot identify their " + "consumers; the operator must supply this mapping. Assign " "only those runtime roles and scopes, change the callers to Entra tokens, and " "verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. " "If identities cannot be supplied yet, keep those callers on APIM; do not " - "recreate master or enable built-in keys as a workaround. A management role " + "enable built-in keys as a workaround. A management role " "such as Contributor does not imply runtime invocation access. Configuration " "phases can complete before this prerequisite is acknowledged; their completion " "does not establish caller cutover." diff --git a/tools/migrate-apim/schemas/plan.schema.json b/tools/migrate-apim/schemas/plan.schema.json index 3b50d636..2fb51942 100644 --- a/tools/migrate-apim/schemas/plan.schema.json +++ b/tools/migrate-apim/schemas/plan.schema.json @@ -117,7 +117,7 @@ }, "prerequisites": { - "description": "Steps the tool cannot perform, surfaced before anything is executed. prereq:caller-rbac requires operator-supplied caller Entra object IDs, principal types, and least-privilege model/alias or tool-server scopes, including for APIM master callers whose shared key cannot identify them. Configuration completion does not establish caller cutover; acknowledgement records the operator's claim, not an automatic conversion or runtime check.", + "description": "Steps the tool cannot perform, surfaced before anything is executed. The default runtime caller migration uses Entra RBAC and creates no API keys. prereq:caller-rbac requires operator-supplied caller Entra object IDs, principal types, and least-privilege model/alias or tool-server scopes; shared source credentials cannot identify their consumers. Configuration completion does not establish caller cutover; acknowledgement records the operator's claim, not an automatic conversion or runtime check.", "type": "array", "items": { "type": "object", diff --git a/tools/migrate-apim/tests/golden/decisions.json b/tools/migrate-apim/tests/golden/decisions.json index 297fe7c8..8d10bf8e 100644 --- a/tools/migrate-apim/tests/golden/decisions.json +++ b/tools/migrate-apim/tests/golden/decisions.json @@ -2133,20 +2133,20 @@ }, "options": [ { - "consequence": "", - "value": "gateway-key-per-consumer" + "consequence": "Default: use Microsoft Entra ID for runtime callers with least-privilege model/tool roles and scopes. Creates no keys; complete prereq:caller-rbac for caller cutover.", + "value": "entra-rbac" }, { - "consequence": "", - "value": "entra-rbac" + "consequence": "Explicit opt-in for non-Entra clients only. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master; distribute the new credentials to those clients separately. No APIM key value is imported.", + "value": "gateway-key-per-consumer" }, { - "consequence": "", + "consequence": "Keep callers on APIM until they are ready for identity cutover.", "value": "retain-in-apim" } ], "proposal": "entra-rbac", - "rationale": "APIM subscription keys are scoped per product, per API, or service-wide. Prefer Entra RBAC with caller object IDs and least-privilege model/tool scopes supplied through prereq:caller-rbac. APIM's built-in master (all-access) subscription is never recreated as an API key, so migration does not undo disabled API built-in keys. gateway-key-per-consumer creates fresh gateway-wide keys for ordinary subscriptions only; no key value is imported.", + "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access.", "shapeDigest": "sha256:8f827c3aa469742d9e2aaba848f579dae5aa9daa81cb9de7c5f9d2fe6990b31d", "source": { "aspect": "subscriptions", @@ -2332,7 +2332,7 @@ "roleDefinitionId": "dce03f8d-857f-4e40-a90d-67770fa6ecd2" } ], - "detail": "APIM's built-in master (all-access) subscription is never recreated as an API key, including when API built-in keys are disabled on the target. Its shared credential cannot identify its consumers, so automatic identity conversion is not possible. Before caller cutover, supply each caller's Entra object ID, principal type, and required model/alias or tool-server resource IDs. Assign only those runtime roles and scopes, change the callers to Entra tokens, and verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. If identities cannot be supplied yet, keep those callers on APIM; do not recreate master or enable built-in keys as a workaround. A management role such as Contributor does not imply runtime invocation access. Configuration phases can complete before this prerequisite is acknowledged; their completion does not establish caller cutover.", + "detail": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Before caller cutover, supply each caller's Entra object ID, principal type, and required model/alias or tool-server resource IDs. APIM's shared credentials cannot identify their consumers; the operator must supply this mapping. Assign only those runtime roles and scopes, change the callers to Entra tokens, and verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. If identities cannot be supplied yet, keep those callers on APIM; do not enable built-in keys as a workaround. A management role such as Contributor does not imply runtime invocation access. Configuration phases can complete before this prerequisite is acknowledged; their completion does not establish caller cutover.", "id": "prereq:caller-rbac", "owner": "azure-administrator", "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC" diff --git a/tools/migrate-apim/tests/test_plan.py b/tools/migrate-apim/tests/test_plan.py index dd9b5422..2a6732eb 100644 --- a/tools/migrate-apim/tests/test_plan.py +++ b/tools/migrate-apim/tests/test_plan.py @@ -1758,10 +1758,37 @@ def test_a_destination_in_the_decision_builds_an_exporter(self, inventory, capab class TestKeysAreOnlyMadeWhenAsked: - def test_entra_rbac_creates_no_keys(self, plan): - item = next(i for i in plan["items"] if i.get("capabilityId") == "key.create") + @pytest.mark.parametrize("subscription_names", [ + ["team-a"], ["master"], ["team-a", "master"], + ]) + def test_the_default_and_accepted_proposal_create_no_key_steps( + self, inventory, capabilities, subscription_names + ): + source = copy.deepcopy(inventory) + source["apim"]["subscriptions"] = [ + s for s in source["apim"]["subscriptions"] if s["name"] in subscription_names + ] + first = build_plan(source, capabilities) + [item] = items_of(first, "subscriptions") assert item["proposal"] == "entra-rbac" + assert item["options"][0]["value"] == "entra-rbac" + assert "no keys" in item["options"][0]["consequence"] assert not (item.get("target") or {}).get("objects") + assert not [s for s in apply_mod.steps_for(first) if s.capability_id == "key.create"] + item["status"] = "adapted" + item["decision"] = item["proposal"] + accepted = build_plan(source, capabilities, previous=first) + [item] = items_of(accepted, "subscriptions") + assert item["status"] == "adapted" + assert not (item.get("target") or {}).get("objects") + assert not [s for s in apply_mod.steps_for(accepted) if s.capability_id == "key.create"] + + def test_key_choice_is_an_explicit_non_entra_exception(self, plan): + [item] = items_of(plan, "subscriptions") + option = next(o for o in item["options"] if o["value"] == "gateway-key-per-consumer") + assert "non-Entra" in option["consequence"] + assert "gateway-wide" in option["consequence"] + assert "master" in option["consequence"] def test_a_key_per_consumer_excludes_the_builtin_master(self, inventory, capabilities): import copy @@ -1816,8 +1843,8 @@ def test_caller_rbac_requires_explicit_identities_and_asset_scopes(self, plan): assert "--scope " in commands[0]["command"] assert "AI Gateway Tools User" in commands[1]["command"] assert "--scope " in commands[1]["command"] - assert "master" in prereq["detail"] assert "cannot identify" in prereq["detail"] + assert prereq["detail"].startswith("Use Microsoft Entra ID for runtime callers.") assert "before acknowledging" in prereq["detail"] assert "configuration" in prereq["detail"].lower() From c37a6ed12b3842cb84b86ff9cad0c98afc0336c5 Mon Sep 17 00:00:00 2001 From: Paul Yuknewicz Date: Thu, 3 Dec 2026 10:32:09 -0800 Subject: [PATCH 3/3] Gate explicit runtime key migration on gateway Owner confirmation Keep Entra as the default. Align key opt-in prerequisites and client guidance with the gateway-wide Phase 2 runtime access contract, without claiming unsupported disableLocalAuth detection. Update the golden plan to match the clarified access choices. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/migrate-apim/ARCHITECTURE.md | 30 +++++++++- tools/migrate-apim/README.md | 58 ++++++++++++++++--- tools/migrate-apim/capabilities/rules.json | 4 +- tools/migrate-apim/migrate_apim/apply.py | 35 +++++++++-- tools/migrate-apim/migrate_apim/plan.py | 31 +++++++++- tools/migrate-apim/schemas/plan.schema.json | 2 +- .../migrate-apim/tests/golden/decisions.json | 6 +- tools/migrate-apim/tests/test_apply.py | 48 +++++++++++++++ tools/migrate-apim/tests/test_plan.py | 18 ++++++ 9 files changed, 208 insertions(+), 24 deletions(-) diff --git a/tools/migrate-apim/ARCHITECTURE.md b/tools/migrate-apim/ARCHITECTURE.md index 66e6abcf..eb7fedf0 100644 --- a/tools/migrate-apim/ARCHITECTURE.md +++ b/tools/migrate-apim/ARCHITECTURE.md @@ -123,8 +123,15 @@ The catalog says what the tool intends to call; the snapshot says what exists. ` Microsoft Entra ID is the default authentication for runtime callers. The planner proposes `entra-rbac` first, explains that it creates no API keys, and produces no -key targets when the operator accepts it. This path works with API built-in keys -disabled. +key targets when the operator accepts it. This path works with gateway-wide +key-based access disabled. + +The Phase 2 runtime access contract defines `properties.disableLocalAuth`: `true` +(off) for new gateways and initialized to `false` (on) for pre-Phase 2 gateways. +Only a gateway Owner can change the setting, with risk acknowledgment when enabling, +subject to Azure Policy. These are contract semantics, not an assertion that the +current API/CLI exposes the setting or that rollout is complete. +Migration does not toggle the target's key-based access setting. `prereq:caller-rbac` is the manual identity cutover boundary. An operator must supply each caller's Entra object ID, principal type, and least-privilege model/alias or @@ -133,7 +140,7 @@ APIM's shared credentials cannot identify their consumers. No catalog capability is claimed for automatic identity discovery or caller role-assignment apply. Configuration phases and caller cutover remain separate. Run every phase in order, -including the empty keys phase on the default path, without a skip or journal +including keys (no key creation on the default path), without a skip or journal override. Configuration completion does not acknowledge the caller prerequisite or prove runtime access. Callers without an identity mapping remain on APIM until that work is done. @@ -144,6 +151,23 @@ master subscription. The planner recognizes master by source resource name or subscription ID, not display name or service-wide scope. Preflight and the key command builder reject master targets in older plans as well. +Plans producing key targets add `prereq:key-based-access`. Execution of the entire +keys phase stops before any step until the operator acknowledges that a gateway +Owner confirmed access is enabled. Rehearsal stays read-only and available; earlier +configuration phases can create the gateway before that confirmation. Returning to +`entra-rbac` removes the key prerequisite. The current AIGateway API definition and +pinned CLI do not expose `disableLocalAuth`, so this is a manual confirmation gate, +not a live state check or automatic toggle. Unsupported state detection remains +explicitly unknown after acknowledgment. If state cannot be established or access +is disabled, stop the opt-in and re-plan for Entra. + +Key metadata read-back does not establish access: Phase 2 allows metadata GET and +DELETE while disabled, but blocks authorized mutations and `listSecrets` with +`409 LocalAuthDisabled`, and rejects runtime keys with `401`. Migrated key clients +use `Authorization: Bearer` or `api-key`, never `x-api-key`, and each named key has +one secret with no secondary key. Backend provider credentials are a separate +contract. + ## The Version Contract When the Azure CLI extension gains a new capability: diff --git a/tools/migrate-apim/README.md b/tools/migrate-apim/README.md index eaf48c8a..787a112d 100644 --- a/tools/migrate-apim/README.md +++ b/tools/migrate-apim/README.md @@ -970,7 +970,11 @@ mechanically retrievable; the plan describes work it cannot itself produce; a st nothing in the plan registers; an object the planner marked as not fully configurable would become a step; or a `Microsoft.ApiManagement/service` shares the target's name, which matters because several CLI commands dispatch by name without `--ids`. Manual prerequisites are raised as notes and -acknowledged with `--acknowledge `. +acknowledged with `--acknowledge `. Key opt-in also raises `keyAccessUnverified`: the current +API/CLI cannot establish gateway-wide key-based access state. Earlier configuration phases can +run, but execution of the entire `keys` phase is gated on Owner confirmation recorded through +`prereq:key-based-access`. This is not a live check, and key metadata is not evidence that access +is enabled. See the [key opt-in requirements](#what-the-last-two-phases-apply) before acknowledging. **The prerequisite note is the list as it stands**, not the list as it was planned: outstanding ones first, acknowledged ones kept below them so what the migration depended on stays on the @@ -1092,8 +1096,13 @@ they drift apart. **Use Microsoft Entra ID for runtime callers.** The default migration creates no API keys. Accept `entra-rbac`, grant each caller the runtime roles it needs on specific models, aliases, or -MCP servers, and switch the caller to Entra tokens. This is the expected path with API built-in -keys disabled. +MCP servers, and switch the caller to Entra tokens. Key-based access is a gateway-wide setting, +not a type of API key. Under the Phase 2 runtime access contract, new gateways default to +`properties.disableLocalAuth: true` (key-based access off); pre-Phase 2 gateways initialize to +`false` (on). Entra remains the migration default for both. The current API definition and pinned +CLI do not expose this property; these are the Phase 2 contract defaults, not a state this tool +has read or a claim that the rollout has completed. Migration does not change an existing +gateway's key-based access setting. Supply each caller's Entra object ID (not application/client ID), principal type, and the full resource IDs of its required assets. `prereq:caller-rbac` gives the role commands; apply does not @@ -1130,23 +1139,56 @@ An alias scope is `/workspaces/default/aliases/ and a call outside the assigned scope using the caller's own identity. See [caller authentication](https://ai.gateway.azure.com/docs/security/authenticate-entra) for tokens and supported identities. If caller identities are not yet known, keep those callers on APIM. -Do not turn built-in keys on or skip a phase as a workaround. +Do not enable key-based access or skip a phase as a workaround for missing caller identities. **Configuration completion is not caller cutover.** Run each configuration phase normally, -including the empty `keys` phase on the default path. No phase needs a skip or journal override. +including `keys`, which creates no keys on the default path. No phase needs a skip or journal override. Configuration completion does not acknowledge `prereq:caller-rbac`. The closing report lists it until the operator records it; acknowledgement is an operator claim, not a runtime test by this tool. **Explicit opt-in: keys for non-Entra clients.** Choose `gateway-key-per-consumer` only for clients that cannot use Entra. This option creates fresh gateway-wide keys for ordinary APIM subscriptions, -carrying their names, not their values. +carrying their names, not their values. It adds `prereq:key-based-access` to the plan. + +**Stop before executing `keys` until a gateway Owner confirms that key-based access is enabled.** +Only a gateway **Owner**, not Contributor or a key administrator, can enable or disable this +gateway-wide setting under the Phase 2 contract. Enabling requires static-key risk acknowledgment +and is subject to Azure Policy. Do not infer the setting from existing key metadata: while +key-based access is off, metadata `GET` and `DELETE` remain available, but authorized create, +update, regeneration, and `listSecrets` calls fail with `409 LocalAuthDisabled`; runtime key +requests fail with `401`. + +The current AIGateway API definition and pinned CLI do not expose `disableLocalAuth`. This tool +cannot detect or change the setting and supplies no property read, API version, or CLI flag for +it. Obtain Owner confirmation through a supported product control. If the state cannot be +established, key-based access is disabled, or Azure Policy forbids it, stop the key opt-in and +choose `entra-rbac`, then re-plan. Do not bypass the phase. + +After the Owner confirms access is enabled and has acknowledged the risks, record that +confirmation before executing the phase: + +```bash +migrate-apim apply --plan plan.json --inventory inventory.json \ + --acknowledge prereq:key-based-access +``` + +The entire `keys` phase refuses execution before any step without this acknowledgment, including +for older plans that must first be regenerated to include the prerequisite. Rehearsal remains +read-only and available. Earlier configuration phases can create the target before the Owner +confirms its state. Acknowledgment records the confirmation, not a live check, and can become +stale if the Owner or policy changes the setting. Do not acknowledge it while access is disabled. + Distribute the replacement credentials and change those clients separately; only the operator -runs `api-key list-secrets`. +runs `api-key list-secrets`. Each named key has **one secret, no secondary key**. Migrated clients +send it using `Authorization: Bearer ` or `api-key: `, **never `x-api-key`**. This is the +gateway-facing contract, not a change to backend provider credentials. Keep secrets out of +artifacts, logs, screenshots, and shell history. APIM's built-in `master` subscription is never recreated. An ordinary subscription is not treated as master just because its display name says "All access" or its scope covers all APIs. Older plans that still target master fail preflight and must be regenerated, not edited to bypass the -check. Do not recreate a global all-access key or enable built-in keys to work around that guard. +check. Entra is the default, so migration never recreates a shared all-access credential. +Do not recreate master or enable key-based access to work around that guard. **`--preflight` also asks for a list to be kept**, once, under the phases it just printed: one entry per phase, ticked from what a run prints. A migration runs one phase per invocation over as many diff --git a/tools/migrate-apim/capabilities/rules.json b/tools/migrate-apim/capabilities/rules.json index 80d51b19..f16ba418 100644 --- a/tools/migrate-apim/capabilities/rules.json +++ b/tools/migrate-apim/capabilities/rules.json @@ -681,7 +681,7 @@ }, { "value": "gateway-key-per-consumer", - "consequence": "Explicit opt-in for non-Entra clients only. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master; distribute the new credentials to those clients separately. No APIM key value is imported." + "consequence": "Explicit opt-in for non-Entra clients only. A gateway Owner must confirm key-based access is enabled with risk acknowledgment, subject to Azure Policy; complete prereq:key-based-access before executing keys. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master. Each named key has one secret, no secondary; clients send Authorization: Bearer or api-key, never x-api-key. Distribute new credentials separately; no APIM key value is imported." }, { "value": "retain-in-apim", @@ -689,7 +689,7 @@ } ], "proposal": "entra-rbac", - "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access." + "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with gateway-wide key-based access disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access." }, { "id": "structural/certificates", diff --git a/tools/migrate-apim/migrate_apim/apply.py b/tools/migrate-apim/migrate_apim/apply.py index 89af543e..30bcd67a 100644 --- a/tools/migrate-apim/migrate_apim/apply.py +++ b/tools/migrate-apim/migrate_apim/apply.py @@ -40,7 +40,7 @@ # for "resolved on the way out" and every one of them must have a resolver; # `$fromExport` had none for several releases, and a marker and its resolver # spelled in two places is how that stayed invisible. -from .plan import OPENAPI_MARKER, is_master_subscription +from .plan import KEY_ACCESS_PREREQUISITE, OPENAPI_MARKER, is_master_subscription from .resolve import ResolveError, resolve_secret SCHEMA_VERSION = "1.0" @@ -266,8 +266,22 @@ def finding(code: str, blocking: bool, message: str, remedy: str = "") -> None: "masterKey", True, "The plan would recreate APIM's built-in master subscription as a gateway API key.", "Re-run plan to remove master key targets. Supply caller object IDs and " - "least-privilege asset scopes through prereq:caller-rbac; do not enable API built-in " - "keys or skip a configuration phase to work around this.", + "least-privilege asset scopes through prereq:caller-rbac; do not enable key-based " + "access or skip a configuration phase to work around this.", + ) + + if any(step.capability_id == "key.create" for step in steps_for(plan)): + finding( + "keyAccessUnverified", False, + "This plan opts into runtime keys. The current API definition and pinned CLI do not " + "expose disableLocalAuth, so this tool cannot detect whether key-based access is " + "enabled. Key metadata read-back does not establish that state.", + "Stop before executing keys. Have a gateway Owner confirm key-based access is " + "enabled, including risk acknowledgment and Azure Policy compliance. Re-plan " + f"older artifacts to include {KEY_ACCESS_PREREQUISITE}, then acknowledge it only " + "after that confirmation. Without it, the entire keys phase refuses execution " + "before any step. Acknowledgement is not a live check; if state cannot be " + "established or access is disabled, choose entra-rbac and re-plan. Do not skip phases.", ) # A secret that cannot be retrieved mechanically stops a step mid-phase. @@ -458,8 +472,9 @@ def _prerequisite_note( remedy = ( "Acknowledge each with --acknowledge once it is done, on its own or alongside any " - "other apply flag. Acknowledgement is recorded and does not gate writing: a gateway " - "builds cleanly without any of them while failing to serve traffic." + "other apply flag. Acknowledgement normally does not gate writing: configuration can " + "complete without proving runtime access. The exception is prereq:key-based-access " + "on the explicit key opt-in: it gates execution of the entire keys phase." ) if contradicted: remedy += ( @@ -811,6 +826,16 @@ def run_phase(self, phase: str) -> list[Step]: "the commands, or pass --skip-rehearsal to go straight to writing." ) steps = [step for step in steps_for(self.plan) if step.phase == phase] + if (self.execute and any(step.capability_id == "key.create" for step in steps) + and KEY_ACCESS_PREREQUISITE not in (self.journal.get("acknowledged") or [])): + raise ApplyError( + "Stop before executing keys: a gateway Owner must confirm key-based access is " + "enabled with the required risk acknowledgment and Azure Policy compliance. " + f"Re-plan if {KEY_ACCESS_PREREQUISITE} is absent, then acknowledge it only " + "after Owner confirmation. This tool cannot detect disableLocalAuth with the " + "current API definition and pinned CLI. If access is disabled or cannot be " + "established, choose entra-rbac and re-plan; do not skip the phase." + ) for index, step in enumerate(steps, 1): # Every object is a serial round trip, and a phase of a dozen takes # minutes. Silence for that long is indistinguishable from a hang. diff --git a/tools/migrate-apim/migrate_apim/plan.py b/tools/migrate-apim/migrate_apim/plan.py index 312529f7..43bdeb7f 100644 --- a/tools/migrate-apim/migrate_apim/plan.py +++ b/tools/migrate-apim/migrate_apim/plan.py @@ -27,6 +27,7 @@ SCHEMA_VERSION = "1.0" GENERATOR_VERSION = "0.1.0" +KEY_ACCESS_PREREQUISITE = "prereq:key-based-access" # Every place the planner chooses a rule, declared where the choosing happens. # `migrate_apim.compile` reads these to decide whether a rule in rules.json can @@ -2136,6 +2137,32 @@ def _reports_telemetry(self) -> bool: def _manual_prerequisites(self) -> None: """Steps the tool cannot perform, surfaced before anything is executed.""" assets = self.inventory.get("assets") or {} + if any(item.get("capabilityId") == "key.create" + and (item.get("target") or {}).get("objects") for item in self.items): + self.prerequisites.append({ + "id": KEY_ACCESS_PREREQUISITE, + "owner": "azure-administrator", + "summary": "Stop before keys: have a gateway Owner confirm key-based access is enabled", + "detail": ( + "Key-based access is a gateway-wide setting, not a kind of API key. Under " + "the Phase 2 contract, properties.disableLocalAuth defaults to true on new " + "gateways; pre-Phase 2 gateways initialize to false. Only a gateway Owner " + "can enable or disable key-based access, with static-key risk acknowledgment " + "when enabling; Azure Policy can deny enablement. Stop before executing the " + "keys phase until the Owner confirms that the target permits key-based " + "access, then acknowledge prereq:key-based-access. If access is disabled or " + "policy forbids it, use entra-rbac instead and re-plan. The current " + "AIGateway API definition and pinned CLI do not expose disableLocalAuth, so " + "this tool cannot detect or change that setting. Do not invent a property " + "read, API version, or CLI flag. If no supported control can establish " + "the state, stop the key opt-in and use Entra. Acknowledgement records an " + "Owner confirmation, not a live check, and can become stale. While disabled, " + "key metadata GET and DELETE remain available, but authorized create, " + "update, regeneration, and listSecrets fail with 409 LocalAuthDisabled; " + "runtime key requests fail with 401. Metadata read-back does not prove " + "that keys work. Complete every configuration phase in order without skips." + ), + }) providers = assets.get("modelProviders") or [] if any((provider.get("auth") or {}).get("mode") == "managedIdentity" for provider in providers): identity = (self.inventory.get("service") or {}).get("identity") or {} @@ -2303,14 +2330,14 @@ def _manual_prerequisites(self) -> None: "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC", "detail": ( "Use Microsoft Entra ID for runtime callers. The default migration creates no " - "API keys and works with API built-in keys disabled. Before caller cutover, " + "API keys and works with gateway-wide key-based access disabled. Before caller cutover, " "supply each caller's Entra object ID, principal type, and required model/alias " "or tool-server resource IDs. APIM's shared credentials cannot identify their " "consumers; the operator must supply this mapping. Assign " "only those runtime roles and scopes, change the callers to Entra tokens, and " "verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. " "If identities cannot be supplied yet, keep those callers on APIM; do not " - "enable built-in keys as a workaround. A management role " + "enable key-based access as a workaround. A management role " "such as Contributor does not imply runtime invocation access. Configuration " "phases can complete before this prerequisite is acknowledged; their completion " "does not establish caller cutover." diff --git a/tools/migrate-apim/schemas/plan.schema.json b/tools/migrate-apim/schemas/plan.schema.json index 2fb51942..bfa4ed4c 100644 --- a/tools/migrate-apim/schemas/plan.schema.json +++ b/tools/migrate-apim/schemas/plan.schema.json @@ -117,7 +117,7 @@ }, "prerequisites": { - "description": "Steps the tool cannot perform, surfaced before anything is executed. The default runtime caller migration uses Entra RBAC and creates no API keys. prereq:caller-rbac requires operator-supplied caller Entra object IDs, principal types, and least-privilege model/alias or tool-server scopes; shared source credentials cannot identify their consumers. Configuration completion does not establish caller cutover; acknowledgement records the operator's claim, not an automatic conversion or runtime check.", + "description": "Steps the tool cannot perform, surfaced before anything is executed. The default runtime caller migration uses Entra RBAC and creates no API keys. prereq:caller-rbac requires operator-supplied caller Entra object IDs, principal types, and least-privilege model/alias or tool-server scopes; shared source credentials cannot identify their consumers. Configuration completion does not establish caller cutover. Plans producing key targets add prereq:key-based-access: the operator must record gateway Owner confirmation that gateway-wide key-based access is enabled with risk acknowledgment, subject to Azure Policy, before any keys-phase execution. The current API definition and pinned CLI do not expose disableLocalAuth, so this is an attestation, not automatic detection or a toggle. Acknowledgment records an operator claim, not a runtime check.", "type": "array", "items": { "type": "object", diff --git a/tools/migrate-apim/tests/golden/decisions.json b/tools/migrate-apim/tests/golden/decisions.json index 8d10bf8e..6cdb3f94 100644 --- a/tools/migrate-apim/tests/golden/decisions.json +++ b/tools/migrate-apim/tests/golden/decisions.json @@ -2137,7 +2137,7 @@ "value": "entra-rbac" }, { - "consequence": "Explicit opt-in for non-Entra clients only. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master; distribute the new credentials to those clients separately. No APIM key value is imported.", + "consequence": "Explicit opt-in for non-Entra clients only. A gateway Owner must confirm key-based access is enabled with risk acknowledgment, subject to Azure Policy; complete prereq:key-based-access before executing keys. Creates fresh gateway-wide keys for ordinary APIM subscriptions, never master. Each named key has one secret, no secondary; clients send Authorization: Bearer or api-key, never x-api-key. Distribute new credentials separately; no APIM key value is imported.", "value": "gateway-key-per-consumer" }, { @@ -2146,7 +2146,7 @@ } ], "proposal": "entra-rbac", - "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access.", + "rationale": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with gateway-wide key-based access disabled. Supply caller object IDs and least-privilege model/tool scopes through prereq:caller-rbac, then switch callers to Entra tokens and verify runtime access.", "shapeDigest": "sha256:8f827c3aa469742d9e2aaba848f579dae5aa9daa81cb9de7c5f9d2fe6990b31d", "source": { "aspect": "subscriptions", @@ -2332,7 +2332,7 @@ "roleDefinitionId": "dce03f8d-857f-4e40-a90d-67770fa6ecd2" } ], - "detail": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with API built-in keys disabled. Before caller cutover, supply each caller's Entra object ID, principal type, and required model/alias or tool-server resource IDs. APIM's shared credentials cannot identify their consumers; the operator must supply this mapping. Assign only those runtime roles and scopes, change the callers to Entra tokens, and verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. If identities cannot be supplied yet, keep those callers on APIM; do not enable built-in keys as a workaround. A management role such as Contributor does not imply runtime invocation access. Configuration phases can complete before this prerequisite is acknowledged; their completion does not establish caller cutover.", + "detail": "Use Microsoft Entra ID for runtime callers. The default migration creates no API keys and works with gateway-wide key-based access disabled. Before caller cutover, supply each caller's Entra object ID, principal type, and required model/alias or tool-server resource IDs. APIM's shared credentials cannot identify their consumers; the operator must supply this mapping. Assign only those runtime roles and scopes, change the callers to Entra tokens, and verify allowed and denied runtime calls before acknowledging prereq:caller-rbac. If identities cannot be supplied yet, keep those callers on APIM; do not enable key-based access as a workaround. A management role such as Contributor does not imply runtime invocation access. Configuration phases can complete before this prerequisite is acknowledged; their completion does not establish caller cutover.", "id": "prereq:caller-rbac", "owner": "azure-administrator", "summary": "Supply caller identities and least-privilege model/tool scopes for Entra RBAC" diff --git a/tools/migrate-apim/tests/test_apply.py b/tools/migrate-apim/tests/test_apply.py index 1bb873c5..9eeb0305 100644 --- a/tools/migrate-apim/tests/test_apply.py +++ b/tools/migrate-apim/tests/test_apply.py @@ -216,11 +216,59 @@ def test_master_only_keys_phase_completes_without_claiming_caller_cutover( assert executor.phase_complete("keys") assert journal["phases"]["keys"]["status"] == "complete" assert not runner.calls + assert not [p for p in plan["prerequisites"] if p["id"] == "prereq:key-based-access"] assert "prereq:caller-rbac" not in journal["acknowledged"] closing = "\n".join(summary.render_verify(journal, plan)) assert "prereq:caller-rbac" in closing assert "does not serve traffic" in closing + def test_key_opt_in_stops_before_any_phase_write_until_owner_confirmation( + self, inventory, settled + ): + key_item = next(i for i in settled["items"] if i["capabilityId"] == "key.create") + key_item["target"] = { + "capability": "key.create", + "objects": [{"name": "team-a", "displayName": "Team A"}], + } + settled["items"].insert(0, { + "id": "item:telemetry/test", "status": "adapted", "capabilityId": "telemetry.create", + "target": {"objects": [{"name": "telemetry", "kind": "ApplicationInsights", + "settings": {"connectionString": "InstrumentationKey=00000000"}}]}, + }) + journal = new_journal(settled) + runner = _Runner() + executor = Executor(settled, inventory, journal, runner=runner, execute=True, + skip_rehearsal=True) + with pytest.raises(ApplyError, match="prereq:key-based-access"): + executor.run_phase("keys") + assert not runner.calls + assert not journal["steps"] + assert not executor.phase_complete("keys") + assert "keys" not in journal.get("phases", {}) + + def test_key_access_acknowledgement_unblocks_normal_execution_not_runtime_verification( + self, inventory, settled + ): + key_item = next(i for i in settled["items"] if i["capabilityId"] == "key.create") + key_item["target"] = { + "capability": "key.create", + "objects": [{"name": "team-a", "displayName": "Team A"}], + } + journal = new_journal(settled) + runner = _Runner(reads={"team-a": {"name": "team-a", "displayName": "Team A"}}) + executor = Executor(settled, inventory, journal, runner=runner) + executor.run_phase("keys") + journal["acknowledged"] = ["prereq:key-based-access"] + executor = Executor(settled, inventory, journal, runner=runner, execute=True) + executor.run_phase("keys") + assert executor.phase_complete("keys") + assert journal["phases"]["keys"]["status"] == "complete" + note = next(f for f in preflight(settled, inventory, journal=journal) + if f["code"] == "keyAccessUnverified") + assert "cannot detect" in note["message"] + assert not note["blocking"] + assert "prereq:caller-rbac" not in journal["acknowledged"] + def test_steps_come_out_in_dependency_order(self, settled): phases = [step.phase for step in steps_for(settled)] assert phases == sorted(phases, key=PHASES.index) diff --git a/tools/migrate-apim/tests/test_plan.py b/tools/migrate-apim/tests/test_plan.py index 2a6732eb..e8adf800 100644 --- a/tools/migrate-apim/tests/test_plan.py +++ b/tools/migrate-apim/tests/test_plan.py @@ -1782,6 +1782,7 @@ def test_the_default_and_accepted_proposal_create_no_key_steps( assert item["status"] == "adapted" assert not (item.get("target") or {}).get("objects") assert not [s for s in apply_mod.steps_for(accepted) if s.capability_id == "key.create"] + assert not [p for p in accepted["prerequisites"] if p["id"] == "prereq:key-based-access"] def test_key_choice_is_an_explicit_non_entra_exception(self, plan): [item] = items_of(plan, "subscriptions") @@ -1807,11 +1808,28 @@ def test_a_key_per_consumer_excludes_the_builtin_master(self, inventory, capabil item = next(i for i in second["items"] if i["id"] == item_id) objects = (item["target"] or {})["objects"] assert [obj["name"] for obj in objects] == ["team-a"] + prereq = next(p for p in second["prerequisites"] if p["id"] == "prereq:key-based-access") + assert "Owner" in prereq["summary"] + assert "risk acknowledgment" in prereq["detail"] + assert "Azure Policy" in prereq["detail"] + assert "cannot detect" in prereq["detail"] + assert not prereq.get("commands") for obj in objects: # The value is the one thing that cannot come across. assert obj["replaces"]["valueCarriedOver"] is False assert "value" not in obj and "primaryKey" not in obj + def test_returning_to_entra_removes_the_key_access_prerequisite(self, inventory, capabilities): + first = build_plan(inventory, capabilities) + [item] = items_of(first, "subscriptions") + item["status"], item["decision"] = "adapted", "gateway-key-per-consumer" + keys = build_plan(inventory, capabilities, previous=first) + [item] = items_of(keys, "subscriptions") + item["decision"] = "entra-rbac" + identity = build_plan(inventory, capabilities, previous=keys) + assert not [p for p in identity["prerequisites"] if p["id"] == "prereq:key-based-access"] + assert not [s for s in apply_mod.steps_for(identity) if s.capability_id == "key.create"] + @pytest.mark.parametrize("name", ["master", "MASTER", "renamed-master"]) def test_master_is_identified_by_resource_name_or_id(self, inventory, name): source = copy.deepcopy(inventory)