diff --git a/tools/migrate-apim/ARCHITECTURE.md b/tools/migrate-apim/ARCHITECTURE.md index 6ee9e698..eb7fedf0 100644 --- a/tools/migrate-apim/ARCHITECTURE.md +++ b/tools/migrate-apim/ARCHITECTURE.md @@ -119,6 +119,55 @@ 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 + +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 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 +tool-server scopes, then assign runtime roles and verify the callers using tokens. +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 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. + +`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. + +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 0612176c..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 @@ -1090,10 +1094,101 @@ 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. +**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. 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 +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 +# 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 \ + --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 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 `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. 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`. 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. 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 e651c725..f16ba418 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. 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", + "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. AI Gateway keys are gateway-wide and no key value can be imported, so every caller is re-keyed." + "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 fa263360..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 +from .plan import KEY_ACCESS_PREREQUISITE, OPENAPI_MARKER, is_master_subscription from .resolve import ResolveError, resolve_secret SCHEMA_VERSION = "1.0" @@ -259,6 +259,31 @@ 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 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. secrets_by_id = {entry["id"]: entry for entry in inventory.get("secrets") or []} needed = _needed_secret_refs(plan) @@ -447,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 += ( @@ -800,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. @@ -1487,6 +1523,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 +1538,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..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 @@ -1895,7 +1896,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 {} ), @@ -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 {} @@ -2278,14 +2305,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": ( + "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." + ), }) if assets.get("mcpServers"): if any( @@ -3385,8 +3441,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 +3460,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..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.", + "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 73d59acd..6cdb3f94 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. 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" }, { - "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. AI Gateway keys are gateway-wide and no key value can be imported, so every caller is re-keyed.", + "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", @@ -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": "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": "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..9eeb0305 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,80 @@ 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 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) @@ -1494,6 +1582,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..e8adf800 100644 --- a/tools/migrate-apim/tests/test_plan.py +++ b/tools/migrate-apim/tests/test_plan.py @@ -1758,12 +1758,40 @@ 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"] + assert not [p for p in accepted["prerequisites"] if p["id"] == "prereq:key-based-access"] - def test_a_key_per_consumer_shapes_one_key_per_subscription(self, inventory, capabilities): + 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 first = build_plan(copy.deepcopy(inventory), capabilities) @@ -1772,16 +1800,72 @@ 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"] + 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) + 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 "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() + class TestAttributesWithNoTargetField: def test_they_are_recorded_on_the_object_rather_than_dropped(self, inventory, capabilities):