<!--
  APIM inbound policy: per-user Entra ID auth and per-developer tiered budgets in front
  of Claude on Microsoft Foundry.

  STATUS: VERIFIED against a live BasicV2 gateway. Auth on 2026-09-01; tiering and the
  budget check on 2026-09-04, on the same instance. What was actually exercised:

    - a named value DOES resolve inside a numeric attribute. tokens-per-minute
      "{{tier-lite-tpm}}" reported x-tokens-remaining 3978 against a 4000 limit, and
      "{{tier-pro-tpm}}" reported 39986 against 40000. This was the design's biggest
      unknown and it holds.
    - the roles claim parses, and precedence works: a token carrying BOTH Claude.User
      and Claude.Tier.Pro selected "pro", not the first-listed role.
    - the fallback is real: a token with Claude.User and no tier role selected "lite"
      and was metered at 4000/35,000,000.
    - the tier-prefixed counter keys are genuinely separate buckets - the same user
      showed a 35,000,000 quota as Lite and a 350,000,000 quota as Pro.
    - Claude.Suspended returned 403 with x-claude-denied-by: admin, AND carried
      x-caller-oid and x-caller-tier. That last part is the whole reason those headers
      are repeated inside return-response; without them the row is anonymous.
    - the budget check fails open. Pointed at an unreachable host it added no measurable
      latency and every request still returned 200.
    - x-caller-tier reaches ApiManagementGatewayLogs once the API diagnostic lists it.

  STILL UNVERIFIED: the 429 path with tier headers attached (no burst was triggered),
  and the budget 403 - there is no budget API deployed yet, so step 5 has only ever
  taken its fail-open branch. See TIERED-QUOTAS.md.

  TEAM GOVERNANCE (added on top of the verified individual controls above, see
  .github/plan/plan-teamGovernanceAndBudgetEnforcement.prompt.md): resolves an
  optional team/profile identity from the same roles claim, in three modes controlled
  by the `team-governance-mode` named value (infra/22-team-governance.bicep) —
  "off" (skip entirely, behavior identical to before this was added), "observe"
  (resolve and stamp headers, meter the team's aggregate token bucket and dollar
  budget, but never deny for identity problems), and "enforce" (also deny a caller
  whose team/profile identity does not resolve cleanly). STILL UNVERIFIED end to end
  on a live gateway pending the promotion rehearsal in Phase 7 of that plan.

  Scope: attach to an API whose serviceUrl is
  https://<resource>.services.ai.azure.com/anthropic
  Requires an API Management v2 tier (BasicV2 / StandardV2 / PremiumV2) for the
  llm-* policies to understand the Anthropic Messages schema.

  Note: avoid writing a doubled-brace named value reference inside these comments.
  Substitution is textual across the whole document, comments included, so an example
  that names a value you have not created will fail the deployment.

  CONTROLS THAT REJECT TRAFFIC HERE, and telling them apart matters operationally:
    403 x-claude-denied-by: admin             - step 4,  Entra Claude.Suspended role
    403 x-claude-denied-by: identity           - step 4b, enforce-mode team/profile
                                                 identity gate (zero or multiple roles)
    403 x-claude-denied-by: user-budget        - step 5,  MTD dollars over the individual
                                                 tier cap
    403 x-claude-denied-by: team-budget        - step 5,  MTD dollars over the team's
                                                 aggregate cap
    429 / 403 x-claude-denied-by: user-token-limit - step 8,  individual tier
                                                 llm-token-limit rate or token quota
    429 / 403 x-claude-denied-by: team-token-limit - step 8b, team profile
                                                 llm-token-limit rate or token quota
-->
<policies>
  <inbound>
    <base />

    <!-- 0. Normalise the credential header.
         Claude Desktop's gateway OIDC flow sends the user token in Authorization.
         Claude Code sends the apiKeyHelper output in x-api-key AND a literal
         "Authorization: Bearer dummy" placeholder alongside it. VERIFIED against
         claude-cli 2.1.233.

         So exists-action="skip" is useless here: Authorization already exists, it
         just contains the word "dummy", and validate-azure-ad-token then rejects it.
         Override only when x-api-key is actually present, which leaves Desktop
         traffic untouched. -->
    <choose>
      <when condition="@(context.Request.Headers.ContainsKey(&quot;x-api-key&quot;))">
        <set-header name="Authorization" exists-action="override">
          <value>@("Bearer " + context.Request.Headers.GetValueOrDefault("x-api-key", ""))</value>
        </set-header>
      </when>
    </choose>

    <!-- 1. Who is calling?
         Gate on an app role, not a group. The groups claim is capped at 200 object
         IDs; past that Entra omits it entirely and emits _claim_names/_claim_sources,
         at which point required-claims fails closed for legitimate users.
         App roles have no overage limit — which is also why the tier and suspension
         signals below are app roles rather than groups. -->
    <validate-azure-ad-token
        tenant-id="{{entra-tenant-id}}"
        header-name="Authorization"
        failed-validation-httpcode="401"
        failed-validation-error-message="Unauthorized. Access token is missing or invalid."
        output-token-variable-name="jwt">
      <audiences>
        <!-- VERIFIED: for a v2 access token (requestedAccessTokenVersion: 2) the aud
             claim is the BARE application ID, not the api:// identifier URI. Only v1
             tokens carry api://<guid>. Getting this wrong produces a flat 401 that
             says nothing about audiences. Check a real token before trusting either. -->
        <audience>{{claude-gateway-audience}}</audience>
      </audiences>
      <required-claims>
        <claim name="roles" match="any">
          <value>Claude.User</value>
        </claim>
      </required-claims>
    </validate-azure-ad-token>

    <!-- 2. Capture the caller's stable identity before the token is discarded.
         oid, not email or UPN — those are mutable.

         Note the &quot; entities. A policy expression in an ATTRIBUTE cannot contain
         a raw double quote; it terminates the attribute and the document stops being
         well-formed XML. Microsoft's own doc samples print raw quotes here, and they
         will not deploy as written. Expressions in ELEMENT content — the <value>
         blocks below — have no such problem. -->
    <set-variable name="callerOid"
                  value="@(((Jwt)context.Variables[&quot;jwt&quot;]).Claims.GetValueOrDefault(&quot;oid&quot;, &quot;unknown&quot;))" />

    <!-- 2a. The roles array, parsed ONCE. Both the tier and the suspension flag come
         out of it, so neither costs a lookup, a cache read, or a network call.

         Do NOT reach for the GetValueOrDefault idiom used for oid above. That overload
         returns COMMA-SEPARATED claim values, so for a multi-valued roles claim it hands
         back "Claude.User,Claude.Tier.Pro" — and .Contains() on that string is a
         substring test that would also match a hypothetical Claude.Tier.ProPlus.
         Claims is IReadOnlyDictionary<string, string[]>; take the array.

         ContainsKey + indexer rather than TryGetValue: no out-parameter, which keeps
         this inside the most conservative reading of what the expression compiler
         accepts. Array.IndexOf rather than LINQ Contains for the same reason — and it
         is an exact element match either way, which is the point. -->
    <set-variable name="callerRoles" value="@{
        var jwt = (Jwt)context.Variables[&quot;jwt&quot;];
        if (!jwt.Claims.ContainsKey(&quot;roles&quot;)) { return new string[0]; }
        var r = jwt.Claims[&quot;roles&quot;];
        return r == null ? new string[0] : r;
    }" />

    <!-- 2b. Tier. Precedence is explicit and descending, so someone holding two tier
         roles deterministically lands in the higher one rather than wherever the
         claim happened to be ordered.

         Falling through to "lite" is deliberate: a token with Claude.User but no tier
         role gets the CHEAPEST tier, not an unlimited one. Combined with "User
         assignment required" on the app registration, there is no path to an
         unmetered request. -->
    <set-variable name="callerTier" value="@{
        var r = (string[])context.Variables[&quot;callerRoles&quot;];
        if (System.Array.IndexOf(r, &quot;Claude.Tier.Pro&quot;) >= 0) { return &quot;pro&quot;; }
        if (System.Array.IndexOf(r, &quot;Claude.Tier.Basic&quot;) >= 0) { return &quot;basic&quot;; }
        return &quot;lite&quot;;
    }" />

    <!-- 2c. Stamp identity onto the request so it reaches the gateway logs.
         Nothing else carries it: ApiManagementGatewayLlmLog has no caller column,
         and GatewayLogs' UserId / ApimSubscriptionId are both empty when auth is
         Entra rather than APIM subscription keys. Without these headers every
         row is anonymous and per-developer reporting is impossible.

         x-caller-tier is what makes the whole budget loop work downstream: the usage
         processor reads it off the log record to know which CostQuota to compare
         against, and the workbook groups by it.

         Placed BEFORE every rejection below, deliberately: a rejected request never
         reaches the backend, and "who is hitting their limit" is exactly the
         question you want answered.

         preferred_username, NOT upn. A v2 access token
         (requestedAccessTokenVersion: 2) has no upn claim at all - the readable
         identity is preferred_username, with "name" carrying the display name.
         Reading upn here logs the literal string "unknown" for every user.

         PRIVACY: preferred_username is an email address. Enabling this puts
         personal data in Log Analytics, and that workspace then inherits a
         retention and access-control obligation. Drop the second header and
         resolve oid in Entra at report time if you would rather it did not. -->
    <set-header name="x-caller-oid" exists-action="override">
      <value>@((string)context.Variables["callerOid"])</value>
    </set-header>
    <set-header name="x-caller-upn" exists-action="override">
      <value>@(((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("preferred_username", "unknown"))</value>
    </set-header>
    <set-header name="x-caller-tier" exists-action="override">
      <value>@((string)context.Variables["callerTier"])</value>
    </set-header>

    <!-- 2d. Team/profile resolution. See infra/22-team-governance.bicep for why this
         reads two parsed JSON blobs (team-role-value -> team, profile-role-value ->
         profile) rather than named values per team: only a policy EXPRESSION can be
         dynamic here, unlike tokens-per-minute below.

         A team role and a profile role are two SEPARATE app-role assignments (see
         admin/configure-claude-teams.sh) — a caller can hold one without the other
         mid-onboarding, or hold a team role paired with the WRONG profile role. Every
         one of those is "ambiguous", not "ok": this policy never guesses which
         profile to bill.

         Skipped in "off" mode so a caller with no team ever pays for a JObject.Parse.
         Populates teamId/teamProfile/teamState even in "observe" mode — nothing here
         enforces yet, that is step 4b below. -->
    <set-variable name="teamGovernanceMode" value="{{team-governance-mode}}" />
    <set-variable name="teamIdentity" value="@{
        var mode = (string)context.Variables[&quot;teamGovernanceMode&quot;];
        var result = new JObject();
        result[&quot;state&quot;] = &quot;disabled&quot;;
        result[&quot;teamId&quot;] = &quot;&quot;;
        result[&quot;teamProfile&quot;] = &quot;&quot;;
        result[&quot;allowedModels&quot;] = new JArray();
        if (mode == &quot;off&quot;) { return result; }

        var teamsMap = JObject.Parse(System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(&quot;{{team-governance-teams-json}}&quot;)));
        var profilesMap = JObject.Parse(System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(&quot;{{team-governance-profiles-json}}&quot;)));
        var roles = (string[])context.Variables[&quot;callerRoles&quot;];

        var matchedTeamCount = 0;
        var matchedTeam = new JObject();
        foreach (var prop in teamsMap.Properties()) {
          if (System.Array.IndexOf(roles, prop.Name) >= 0) {
            matchedTeamCount++;
            matchedTeam = (JObject)prop.Value;
          }
        }
        var matchedProfileCount = 0;
        var matchedProfileRoleValue = &quot;&quot;;
        var matchedProfile = new JObject();
        foreach (var prop in profilesMap.Properties()) {
          if (System.Array.IndexOf(roles, prop.Name) >= 0) {
            matchedProfileCount++;
            matchedProfileRoleValue = prop.Name;
            matchedProfile = (JObject)prop.Value;
          }
        }

        if (matchedTeamCount == 0 &amp;&amp; matchedProfileCount == 0) {
            result[&quot;state&quot;] = &quot;missing&quot;;
            return result;
        }
        if (matchedTeamCount != 1 || matchedProfileCount != 1) {
            result[&quot;state&quot;] = &quot;ambiguous&quot;;
            return result;
        }

        var expectedProfileRoleValue = (string)matchedTeam[&quot;profileRoleValue&quot;];
        if (matchedProfileRoleValue != expectedProfileRoleValue) {
            // Exactly one team role and one profile role present, but they do not name
            // each other - e.g. a Power team member wearing the Regular profile role.
            // Never bill against a profile the team's own mapping does not expect.
            result[&quot;state&quot;] = &quot;ambiguous&quot;;
            return result;
        }

        result[&quot;state&quot;] = &quot;ok&quot;;
        result[&quot;teamId&quot;] = (string)matchedTeam[&quot;id&quot;];
        result[&quot;teamProfile&quot;] = (string)matchedProfile[&quot;name&quot;];
        result[&quot;allowedModels&quot;] = (JArray)matchedTeam[&quot;allowedModels&quot;];
        return result;
    }" />
    <set-header name="x-caller-team-id" exists-action="override">
      <value>@((string)((JObject)context.Variables["teamIdentity"])["teamId"])</value>
    </set-header>
    <set-header name="x-caller-team-profile" exists-action="override">
      <value>@((string)((JObject)context.Variables["teamIdentity"])["teamProfile"])</value>
    </set-header>
    <set-header name="x-team-governance-state" exists-action="override">
      <value>@((string)((JObject)context.Variables["teamIdentity"])["state"])</value>
    </set-header>

    <!-- 3. Serve GET /v1/models from the gateway.
         Claude Desktop probes this at launch to populate its model picker, and
         Foundry does not implement it — it returns 404 api_not_supported.
         Answering here means Desktop's Model discovery works and the
         model list is managed centrally, so no device needs one pushed to it.
         This sits AFTER validation, so the list is still behind the app role.

         MOVED AHEAD of the budget checks (it used to sit just before the backend).
         Two reasons: a launch probe should not trigger a budget callout, and a
         suspended developer's client should still start up cleanly and fail on the
         actual message call with a readable error, rather than appearing broken. -->
    <choose>
      <when condition="@(context.Request.Method == &quot;GET&quot; &amp;&amp; context.Request.Url.Path.Contains(&quot;/models&quot;))">
        <return-response>
          <set-status code="200" reason="OK" />
          <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
          </set-header>
          <set-body>@{
              var catalog = JArray.Parse(@"[
                {""type"":""model"",""id"":""claude-sonnet-5"",""display_name"":""Claude Sonnet 5"",""created_at"":""2026-01-01T00:00:00Z""},
                {""type"":""model"",""id"":""claude-haiku-4-5"",""display_name"":""Claude Haiku 4.5"",""created_at"":""2025-10-01T00:00:00Z""},
                {""type"":""model"",""id"":""claude-opus-5"",""display_name"":""Claude Opus 5"",""created_at"":""2026-01-01T00:00:00Z""}
              ]");
              var mode = (string)context.Variables["teamGovernanceMode"];
              var identity = (JObject)context.Variables["teamIdentity"];
              var state = (string)identity["state"];
              var allowedModels = ((JArray)identity["allowedModels"]).ToObject&lt;string[]&gt;();
              var data = new JArray();
              foreach (JObject model in catalog) {
                if (mode != "enforce" || (state == "ok" &amp;&amp; System.Array.IndexOf(allowedModels, (string)model["id"]) &gt;= 0)) {
                  data.Add(model);
                }
              }
              var result = new JObject();
              result["data"] = data;
              result["has_more"] = false;
              result["first_id"] = data.Count == 0 ? null : (string)((JObject)data[0])["id"];
              result["last_id"] = data.Count == 0 ? null : (string)((JObject)data[data.Count - 1])["id"];
              return result.ToString(Newtonsoft.Json.Formatting.None);
          }</set-body>
        </return-response>
      </when>
    </choose>

    <!-- 4. Manual suspension, by app role. The admin lever: add someone to the
         Claude.Suspended group and they stop, visibly and reversibly, with the
         change captured in the Entra audit log.

         Costs nothing — the roles array is already parsed. It takes effect on the
         caller's NEXT token, not this one, because that is when the claim changes.
         Group membership is not a Continuous Access Evaluation trigger, so there is
         no way to force it sooner; budget enforcement below is the fast path.

         NOTE the identity headers repeated inside return-response. return-response
         aborts the pipeline, so neither the outbound nor the on-error section runs
         and the headers set at step 2c never reach the client or the response log.
         Without these two lines every deliberate rejection is anonymous — which is
         precisely the row you want attributed. -->
    <choose>
      <when condition="@(System.Array.IndexOf((string[])context.Variables[&quot;callerRoles&quot;], &quot;Claude.Suspended&quot;) >= 0)">
        <return-response>
          <set-status code="403" reason="Suspended" />
          <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
          </set-header>
          <set-header name="x-claude-denied-by" exists-action="override">
            <value>admin</value>
          </set-header>
          <set-header name="x-caller-oid" exists-action="override">
            <value>@((string)context.Variables["callerOid"])</value>
          </set-header>
          <set-header name="x-caller-tier" exists-action="override">
            <value>@((string)context.Variables["callerTier"])</value>
          </set-header>
          <set-header name="x-caller-team-id" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamId"])</value>
          </set-header>
          <set-header name="x-caller-team-profile" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamProfile"])</value>
          </set-header>
          <set-header name="x-team-governance-state" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["state"])</value>
          </set-header>
          <set-body>{"type":"error","error":{"type":"permission_error","message":"Your Claude access has been suspended. Contact the platform team."}}</set-body>
        </return-response>
      </when>
    </choose>

    <!-- 4b. Team identity gate. Only bites in "enforce" mode — "off" never resolves a
         non-disabled state (step 2d short-circuits), and "observe" is deliberately a
         no-deny reconciliation window: see infra/22-team-governance.bicep and
         TIERED-QUOTAS.md for the off -> observe -> enforce promotion path. Once
         promoted, a caller who is not cleanly "ok" — no team/profile role at all, or
         more than one, or a team/profile pairing that does not match — is denied
         attributably rather than silently billed against the wrong bucket or none. -->
    <choose>
      <when condition="@((string)context.Variables[&quot;teamGovernanceMode&quot;] == &quot;enforce&quot; &amp;&amp; (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;state&quot;] != &quot;ok&quot;)">
        <return-response>
          <set-status code="403" reason="Team identity required" />
          <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
          </set-header>
          <set-header name="x-claude-denied-by" exists-action="override">
            <value>identity</value>
          </set-header>
          <set-header name="x-caller-oid" exists-action="override">
            <value>@((string)context.Variables["callerOid"])</value>
          </set-header>
          <set-header name="x-caller-tier" exists-action="override">
            <value>@((string)context.Variables["callerTier"])</value>
          </set-header>
          <set-header name="x-caller-team-id" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamId"])</value>
          </set-header>
          <set-header name="x-caller-team-profile" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamProfile"])</value>
          </set-header>
          <set-header name="x-team-governance-state" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["state"])</value>
          </set-header>
          <set-body>{"type":"error","error":{"type":"permission_error","message":"Claude access requires exactly one team role and one matching team profile role. Contact the platform team to complete your team assignment."}}</set-body>
        </return-response>
      </when>
    </choose>

    <!-- 4c. Per-team model authorization. The body is preserved because Foundry still
         needs the original stream after this policy reads the model. Observe/off modes
         deliberately do not parse or deny, preserving the staged governance rollout. -->
    <set-variable name="requestedModel" value="@{
        if ((string)context.Variables[&quot;teamGovernanceMode&quot;] != &quot;enforce&quot; ||
            (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;state&quot;] != &quot;ok&quot; ||
            context.Request.Method != &quot;POST&quot; || !context.Request.Url.Path.Contains(&quot;/messages&quot;)) {
          return &quot;&quot;;
        }
        var body = context.Request.Body.As&lt;JObject&gt;(preserveContent: true);
        return (string)body[&quot;model&quot;] ?? &quot;&quot;;
    }" />
    <choose>
      <when condition="@((string)context.Variables[&quot;requestedModel&quot;] != &quot;&quot; &amp;&amp; System.Array.IndexOf(((JArray)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;allowedModels&quot;]).ToObject&lt;string[]&gt;(), (string)context.Variables[&quot;requestedModel&quot;]) &lt; 0)">
        <return-response>
          <set-status code="403" reason="Model not allowed" />
          <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
          </set-header>
          <set-header name="x-claude-denied-by" exists-action="override">
            <value>team-model-policy</value>
          </set-header>
          <set-header name="x-caller-oid" exists-action="override">
            <value>@((string)context.Variables["callerOid"])</value>
          </set-header>
          <set-header name="x-caller-tier" exists-action="override">
            <value>@((string)context.Variables["callerTier"])</value>
          </set-header>
          <set-header name="x-caller-team-id" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamId"])</value>
          </set-header>
          <set-header name="x-caller-team-profile" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamProfile"])</value>
          </set-header>
          <set-header name="x-team-governance-state" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["state"])</value>
          </set-header>
          <set-body>{"type":"error","error":{"type":"permission_error","message":"The requested Claude model is not enabled for your team. Contact the platform team to request access."}}</set-body>
        </return-response>
      </when>
    </choose>

    <!-- 5. The dollar budget. The ONLY thing in this pipeline that leaves the
         gateway, and it is built to be survivable.

         Shape: read a cached verdict; on a miss, ask the budget API; cache for 30s.
         At 100k developers that is roughly active_users/30 requests per second
         against the budget API, not one per request. The 30s TTL is also the
         staleness bound, and therefore the overspend window: tokens-per-minute x 30s
         x the worst-case price is about $1.50 on the Pro tier.

         IT FAILS OPEN, DELIBERATELY. ignore-error="true", a 2 second timeout, and
         anything that is not an explicit 402 counts as "ok". A budget-service or
         Redis outage must not take 100k developers offline — step 8's token quota is
         still enforcing synchronously throughout, which is the entire reason that
         backstop is sized the way it is.

         The cache fails open too, and not by accident: when APIM cannot reach its
         cache it does not raise, it returns null to the calling expression. The
         ContainsKey guard below is the documented fallback that behaviour requires.

         402 Payment Required rather than a JSON body: the verdict is a status code,
         so there is no body to parse, no generic type argument to escape into an XML
         attribute, and no ambiguity about what a malformed response means.

         v2, COMBINED: one call now answers for the user's OWN budget and, when the
         caller resolved to a team at step 2d, that team's budget too — see
         snippets/18-budget-api/function_app.py "TEAM GOVERNANCE (v2)". This is the
         one case a response body IS read, and it is a two-word constant ("user" /
         "team"), only on the 402 path, purely so the denial can be attributed instead
         of both scopes collapsing into a single "budget" reason.

         teamId is appended EMPTY for a caller with no resolved team ("missing",
         "ambiguous", or governance "off") — never (string)null, so string
         concatenation cannot literally send the four characters "null" as a query
         value. The v2 endpoint treats an empty teamId as "skip the team check",
         which keeps this one call correct for every caller regardless of team state.

         cache-lookup-value can only be used ONCE per policy section and is not
         allowed inside a policy fragment. This is that one use. -->
    <set-variable name="budgetTeamId" value="@{
        var identity = (JObject)context.Variables[&quot;teamIdentity&quot;];
        return (string)identity[&quot;state&quot;] == &quot;ok&quot; ? (string)identity[&quot;teamId&quot;] : &quot;&quot;;
    }" />
    <cache-lookup-value
        key="@(&quot;bud:v2:&quot; + (string)context.Variables[&quot;budgetTeamId&quot;] + &quot;:&quot; + (string)context.Variables[&quot;callerOid&quot;])"
        variable-name="overBudget"
        caching-type="prefer-external" />
    <choose>
      <when condition="@(!context.Variables.ContainsKey(&quot;overBudget&quot;))">
        <send-request mode="new" response-variable-name="budResp" timeout="2" ignore-error="true">
          <set-url>@("{{budget-api-base-url}}/v1/budget/v2/" + (string)context.Variables["callerOid"] + "?teamId=" + (string)context.Variables["budgetTeamId"])</set-url>
          <set-method>GET</set-method>
          <!-- ignore-error="true" here as well, and it is NOT redundant. send-request's
               own ignore-error covers the HTTP call; token acquisition happens while
               composing the request, so a bad audience or a missing app registration
               would throw before send-request ever gets to swallow anything. Left at the
               default this element is the one thing in the budget check that can 500 a
               request instead of failing open — which would invert the entire design. -->
          <authentication-managed-identity resource="{{budget-api-audience}}" ignore-error="true" />
        </send-request>
        <set-variable name="overBudget" value="@{
            if (!context.Variables.ContainsKey(&quot;budResp&quot;)) { return &quot;ok&quot;; }
            var r = (IResponse)context.Variables[&quot;budResp&quot;];
            if (r == null || r.StatusCode != 402) { return &quot;ok&quot;; }
            // Read the body ONLY on 402 — every other status, including a malformed or
            // unreachable response, already resolved to &quot;ok&quot; above and never touches
            // the body at all.
            var body = r.Body.As&lt;string&gt;(preserveContent: false);
            return body == &quot;team&quot; ? &quot;team&quot; : &quot;user&quot;;
        }" />
        <cache-store-value
            key="@(&quot;bud:v2:&quot; + (string)context.Variables[&quot;budgetTeamId&quot;] + &quot;:&quot; + (string)context.Variables[&quot;callerOid&quot;])"
            value="@((string)context.Variables[&quot;overBudget&quot;])"
            duration="30" />
      </when>
    </choose>
    <choose>
      <when condition="@((string)context.Variables[&quot;overBudget&quot;] == &quot;user&quot; || (string)context.Variables[&quot;overBudget&quot;] == &quot;team&quot;)">
        <return-response>
          <set-status code="403" reason="Budget exceeded" />
          <set-header name="Content-Type" exists-action="override">
            <value>application/json</value>
          </set-header>
          <set-header name="x-claude-denied-by" exists-action="override">
            <value>@(((string)context.Variables["overBudget"] == "team") ? "team-budget" : "user-budget")</value>
          </set-header>
          <set-header name="x-caller-oid" exists-action="override">
            <value>@((string)context.Variables["callerOid"])</value>
          </set-header>
          <set-header name="x-caller-tier" exists-action="override">
            <value>@((string)context.Variables["callerTier"])</value>
          </set-header>
          <set-header name="x-caller-team-id" exists-action="override">
            <value>@((string)context.Variables["budgetTeamId"])</value>
          </set-header>
          <set-header name="x-caller-team-profile" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["teamProfile"])</value>
          </set-header>
          <set-header name="x-team-governance-state" exists-action="override">
            <value>@((string)((JObject)context.Variables["teamIdentity"])["state"])</value>
          </set-header>
          <set-body>@{
              var overScope = (string)context.Variables["overBudget"];
              var message = overScope == "team"
                  ? "Monthly Claude budget exhausted for your team. It resets on the 1st. Contact the platform team if you need a change."
                  : "Monthly Claude budget exhausted for your tier. It resets on the 1st. Contact the platform team if you need a tier change.";
              return "{\"type\":\"error\",\"error\":{\"type\":\"permission_error\",\"message\":\"" + message + "\"}}";
          }</set-body>
        </return-response>
      </when>
    </choose>

    <!-- 6. Mint the gateway's own token and OVERWRITE the user's.
         The user token must not reach Foundry: wrong audience, and forwarding it
         leaks a user credential to the backend.

         Deliberately AFTER the two rejections above — there is no reason to mint a
         Foundry credential for a request that is about to be refused.

         resource: Foundry's /anthropic surface requires scope
         https://ai.azure.com/.default — NOT https://cognitiveservices.azure.com,
         which is what every OpenAI-flavoured APIM sample uses. No Microsoft doc
         shows this value inside authentication-managed-identity, but it is
         VERIFIED correct — Foundry returned a real completion through it.
         ignore-error="false" makes a credential failure loud
         instead of forwarding an unauthenticated request. -->
    <authentication-managed-identity
        resource="https://ai.azure.com"
        output-token-variable-name="foundry-token"
        ignore-error="false" />
    <set-header name="Authorization" exists-action="override">
      <value>@("Bearer " + (string)context.Variables["foundry-token"])</value>
    </set-header>

    <!-- 7. Anthropic wire requirements. Drop any inbound x-api-key so it cannot
         race the bearer token we just set. -->
    <set-header name="anthropic-version" exists-action="skip">
      <value>2023-06-01</value>
    </set-header>
    <set-header name="x-api-key" exists-action="delete" />

    <!-- 8. Per-tier token governance, keyed on the real human rather than a shared
         secret. VERIFIED to throttle streamed traffic: tokens-per-minute returns 429
         with Retry-After, token-quota returns 403 naming the reset time.

         WHY THREE BRANCHES AND NOT ONE PARAMETERISED ELEMENT: tokens-per-minute does
         not accept policy expressions. Only counter-key, token-quota and
         token-quota-period do. Named values are the one dynamic route left, because
         their substitution is textual and happens before the attribute is
         interpreted — so the numbers live in 04-apim-gateway.bicep and can be retuned
         without touching this file.

         WHY THE COUNTER-KEY IS TIER-PREFIXED: the v2 tiers use a token bucket, and
         reusing one counter key with inconsistent tokens-per-minute values is
         documented to behave unpredictably. Prefixing gives each tier its own bucket.
         The cost is that moving someone between tiers mints a fresh counter and a
         fresh monthly token allowance — their DOLLAR budget is unaffected, because
         that lives in Redis keyed on oid alone, which is another reason dollars are
         the real control and this is the backstop.

         WHAT THIS IS FOR: it is sized at the tier budget divided by the CHEAPEST
         model rate, so it does not bind before the dollar cap for anyone using cheap
         models. Its real job is to be the ceiling during the window when step 5 is
         failing open.

         Counters are per gateway - they do not aggregate across regions or
         workspaces. v2 tiers use a token bucket, so an initial burst equal to
         tokens-per-minute is allowed, and it refills continuously. Do not size a TEST
         limit so high that a call refills before you can observe the debit; that
         reads as "streams aren't counted".

         x-tokens-remaining on a streamed 200 is emitted BEFORE the completion is
         charged, so it under-reports that request's own usage. Use GatewayLlmLogs
         for accounting, not this header.

         enforcementScope is set immediately before EACH llm-token-limit call below,
         never after. llm-token-limit throws straight to on-error rather than
         returning, so a variable only reflects which branch was ATTEMPTING to run,
         not which one is done — which is exactly what on-error needs to attribute a
         429/403 to "user-token-limit" or "team-token-limit" without a body to read,
         matching the user-budget/team-budget naming step 5 already uses. -->
    <set-variable name="enforcementScope" value="user-token-limit" />
    <choose>
      <when condition="@((string)context.Variables[&quot;callerTier&quot;] == &quot;pro&quot;)">
        <llm-token-limit
            counter-key="@(&quot;pro:&quot; + (string)context.Variables[&quot;callerOid&quot;])"
            tokens-per-minute="{{tier-pro-tpm}}"
            token-quota="{{tier-pro-token-quota}}"
            token-quota-period="Monthly"
            estimate-prompt-tokens="false"
            tokens-consumed-header-name="x-tokens-consumed"
            remaining-tokens-header-name="x-tokens-remaining"
            remaining-quota-tokens-header-name="x-quota-remaining" />
      </when>
      <when condition="@((string)context.Variables[&quot;callerTier&quot;] == &quot;basic&quot;)">
        <llm-token-limit
            counter-key="@(&quot;basic:&quot; + (string)context.Variables[&quot;callerOid&quot;])"
            tokens-per-minute="{{tier-basic-tpm}}"
            token-quota="{{tier-basic-token-quota}}"
            token-quota-period="Monthly"
            estimate-prompt-tokens="false"
            tokens-consumed-header-name="x-tokens-consumed"
            remaining-tokens-header-name="x-tokens-remaining"
            remaining-quota-tokens-header-name="x-quota-remaining" />
      </when>
      <otherwise>
        <llm-token-limit
            counter-key="@(&quot;lite:&quot; + (string)context.Variables[&quot;callerOid&quot;])"
            tokens-per-minute="{{tier-lite-tpm}}"
            token-quota="{{tier-lite-token-quota}}"
            token-quota-period="Monthly"
            estimate-prompt-tokens="false"
            tokens-consumed-header-name="x-tokens-consumed"
            remaining-tokens-header-name="x-tokens-remaining"
            remaining-quota-tokens-header-name="x-quota-remaining" />
      </otherwise>
    </choose>

    <!-- 8b. Aggregate team token governance. Skipped entirely in "off" mode and for
         any caller whose team identity did not resolve to "ok" — same reasoning as
         step 4b: never bucket spend or throttling against a team the caller was not
         cleanly and unambiguously assigned to. In "observe" mode this DOES run and
         DOES throttle: unlike the 4b identity gate (which only denies in "enforce"),
         a resolved team's aggregate ceiling is a real shared resource from the first
         moment its members start sending traffic, so this is not gated on
         enforcement mode the way 4b is.

         COUNTER-KEY IS PROFILE-AND-TEAM-PREFIXED, NOT PER-USER: this is the whole
         point of an aggregate cap — every member of a team shares one bucket. Profile
         is folded into the key alongside teamId (not just teamId alone) so that if a
         team's profile is ever changed via the config, the rename mints a fresh
         counter rather than inheriting a partially-spent bucket sized for the OLD
         profile's limits — the same reasoning step 8 gives for tier-prefixing above.

         Falls back to team-profile-default-tpm/-token-quota for any profile name
         that is not "power" or "regular" — see infra/22-team-governance.bicep, which
         provisions that fallback named value pair alongside the per-profile ones so
         this branch is never left with an undefined named value if a new profile is
         ever added to config before the gateway module is redeployed. -->
    <choose>
      <when condition="@((string)context.Variables[&quot;teamGovernanceMode&quot;] != &quot;off&quot; &amp;&amp; (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;state&quot;] == &quot;ok&quot;)">
        <set-variable name="enforcementScope" value="team-token-limit" />
        <choose>
          <when condition="@((string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;teamProfile&quot;] == &quot;power&quot;)">
            <llm-token-limit
                counter-key="@(&quot;team:power:&quot; + (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;teamId&quot;])"
                tokens-per-minute="{{team-profile-power-tpm}}"
                token-quota="{{team-profile-power-token-quota}}"
                token-quota-period="Monthly"
                estimate-prompt-tokens="false"
                tokens-consumed-header-name="x-team-tokens-consumed"
                remaining-tokens-header-name="x-team-tokens-remaining"
                remaining-quota-tokens-header-name="x-team-quota-remaining" />
          </when>
          <when condition="@((string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;teamProfile&quot;] == &quot;regular&quot;)">
            <llm-token-limit
                counter-key="@(&quot;team:regular:&quot; + (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;teamId&quot;])"
                tokens-per-minute="{{team-profile-regular-tpm}}"
                token-quota="{{team-profile-regular-token-quota}}"
                token-quota-period="Monthly"
                estimate-prompt-tokens="false"
                tokens-consumed-header-name="x-team-tokens-consumed"
                remaining-tokens-header-name="x-team-tokens-remaining"
                remaining-quota-tokens-header-name="x-team-quota-remaining" />
          </when>
          <otherwise>
            <llm-token-limit
                counter-key="@(&quot;team:default:&quot; + (string)((JObject)context.Variables[&quot;teamIdentity&quot;])[&quot;teamId&quot;])"
                tokens-per-minute="{{team-profile-default-tpm}}"
                token-quota="{{team-profile-default-token-quota}}"
                token-quota-period="Monthly"
                estimate-prompt-tokens="false"
                tokens-consumed-header-name="x-team-tokens-consumed"
                remaining-tokens-header-name="x-team-tokens-remaining"
                remaining-quota-tokens-header-name="x-team-quota-remaining" />
          </otherwise>
        </choose>
        <set-variable name="enforcementScope" value="user-token-limit" />
      </when>
    </choose>

    <!-- Caps: 5 dimensions, 100 unique values per dimension, 1000 active time
         series per namespace. Beyond those, data is silently discarded — which is why
         the per-user dimension this policy used to carry is GONE. At 100k developers
         it exceeded the cap and threw away most of the series without saying so.
         Tier has three values and fits comfortably.

         Treat this as best-effort regardless: on the live BasicV2 test it produced no
         custom metric namespace at all. GatewayLlmLogs is the reporting path. -->
    <llm-emit-token-metric namespace="claude-gateway">
      <dimension name="Tier" value="@((string)context.Variables[&quot;callerTier&quot;])" />
      <dimension name="API ID" />
    </llm-emit-token-metric>

    <set-backend-service base-url="https://{{foundry-resource-name}}.services.ai.azure.com/anthropic" />
  </inbound>

  <backend>
    <!-- buffer-response="false" is mandatory for SSE. Without it, streamed events
         are held rather than relayed. Note the 4-minute idle timeout enforced by
         the load balancer inside APIM — long "thinking" turns can hit it.

         It is also the reason the accounting pipeline is fed by a diagnostic
         destination rather than by an outbound policy: with buffering off, the
         outbound section runs when the response STARTS, so it cannot see final token
         counts. The diagnostic record is written after the stream ends. -->
    <forward-request timeout="600" buffer-response="false" />
  </backend>

  <outbound>
    <base />
    <!-- Identity on the RESPONSE as well as the request. Required, not belt-and-braces:
         a throttled request never reaches the backend, so backend.request.headers is
         empty on every 429 and 403 - precisely the rows where "who hit their limit?"
         is the question. VERIFIED: a 429 carries x-caller-oid only via this path.
         Query the two together:
           coalesce(BackendRequestHeaders['x-caller-oid'], ResponseHeaders['x-caller-oid']) -->
    <set-header name="x-caller-oid" exists-action="override">
      <value>@((string)context.Variables.GetValueOrDefault("callerOid", "unknown"))</value>
    </set-header>
    <set-header name="x-caller-tier" exists-action="override">
      <value>@((string)context.Variables.GetValueOrDefault("callerTier", "unknown"))</value>
    </set-header>
    <!-- ContainsKey rather than GetValueOrDefault: teamIdentity is a JObject, set at
         step 2d before anything that can reach this far, but guarded anyway rather
         than assumed. -->
    <set-header name="x-caller-team-id" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["teamId"] : "")</value>
    </set-header>
    <set-header name="x-caller-team-profile" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["teamProfile"] : "")</value>
    </set-header>
    <set-header name="x-team-governance-state" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["state"] : "disabled")</value>
    </set-header>
  </outbound>

  <on-error>
    <base />
    <!-- on-error is what actually runs when llm-token-limit rejects. Without this
         block, throttle events are anonymous. It does NOT run for the return-response
         rejections at steps 4, 4b and 5 — those set their own headers inline.

         x-claude-denied-by here is read from enforcementScope, set immediately before
         whichever llm-token-limit call was in flight when the throw happened — see
         the comment at step 8. It is only meaningful for THIS on-error path; the
         return-response steps set their own denial reason directly and never reach
         here. -->
    <set-header name="x-caller-oid" exists-action="override">
      <value>@((string)context.Variables.GetValueOrDefault("callerOid", "unknown"))</value>
    </set-header>
    <set-header name="x-caller-tier" exists-action="override">
      <value>@((string)context.Variables.GetValueOrDefault("callerTier", "unknown"))</value>
    </set-header>
    <set-header name="x-claude-denied-by" exists-action="override">
      <value>@((string)context.Variables.GetValueOrDefault("enforcementScope", "user-token-limit"))</value>
    </set-header>
    <set-header name="x-caller-team-id" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["teamId"] : "")</value>
    </set-header>
    <set-header name="x-caller-team-profile" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["teamProfile"] : "")</value>
    </set-header>
    <set-header name="x-team-governance-state" exists-action="override">
      <value>@(context.Variables.ContainsKey("teamIdentity") ? (string)((JObject)context.Variables["teamIdentity"])["state"] : "disabled")</value>
    </set-header>
  </on-error>
</policies>
