Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions tools/migrate-apim/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
105 changes: 100 additions & 5 deletions tools/migrate-apim/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <id>`.
acknowledged with `--acknowledge <id>`. 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
Expand Down Expand Up @@ -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 <caller-object-id> --assignee-principal-type <principal-type> \
--scope <model-or-alias-resource-id>
az role assignment create --role 'AI Gateway Tools User' \
--assignee-object-id <caller-object-id> --assignee-principal-type <principal-type> \
--scope <tool-server-resource-id>

# 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 `<gateway-resource-id>/workspaces/default/aliases/<alias-name>`; an MCP scope is
`<gateway-resource-id>/workspaces/default/toolServers/<server-name>`. 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 <key>` or `api-key: <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
Expand Down
17 changes: 15 additions & 2 deletions tools/migrate-apim/capabilities/rules.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
53 changes: 50 additions & 3 deletions tools/migrate-apim/migrate_apim/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -447,8 +472,9 @@ def _prerequisite_note(

remedy = (
"Acknowledge each with --acknowledge <id> 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 += (
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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"],
Expand Down
Loading