APIM Global Policy Implementation
This page documents the global Rome APIM policy as deployed. It is based on
the Terraform and environment policy files under
rome-ion/infrastructure/spoke/apim, rather than on a generic APIM design.
The global policy authenticates the caller, validates customer-tenant status,
creates trusted request context, applies backend concurrency, forwards the
request, and invokes shared trace fragments. API and operation policies extend
this baseline through <base />.
Source and environment selection
Terraform selects one policy file using the environment short code:
module "rome-apim-global-policy" {
depends_on = [module.rome-apim, module.rome-apim-policy-fragments]
source = "<approved-api-management-policy-module>"
api_management_id = module.rome-apim.apim_id
apim_policy_globals = {
customer_concurrency = 20
}
apim_policy = {
apim = "${path.cwd}/apim_policies/apim_global_policy_${var.environment_short}.xml"
}
}
The deployed files are apim_global_policy_apa.xml,
apim_global_policy_bta.xml, apim_global_policy_gma.xml, and
apim_global_policy_prd.xml. Their control flow is equivalent, but their
allowed audiences and backend concurrency are environment-specific.
| Environment | Policy suffix | Deployed per-API concurrency |
|---|---|---|
| Alpha | apa | 30 |
| Beta | bta | 30 |
| Gamma | gma | 200 |
| Production | prd | 200 |
The Terraform input customer_concurrency = 20 does not currently determine the
hard-coded XML values. This configuration drift must be resolved before treating
that input as authoritative.
Deployed execution flow
The initial tid parse is only routing input for tenant lookup. It is not an
authentication decision. Trust is established only after validate-jwt
succeeds. A future implementation should avoid allowing unvalidated claims to
select unrestricted destinations; the tenant-validation URL must remain a fixed,
controlled base with only the tenant identifier appended.
Inbound execution order
| Order | Policy implementation | Effective behavior | Failure behavior |
|---|---|---|---|
| 1 | check-header | Requires a case-sensitive Authorization header. | APIM returns 401 Not authorized. |
| 2 | set-header | Preserves a caller-supplied X-Transaction-Id; otherwise generates a time/GUID-based value. | Policy evaluation fails if the expression cannot execute. |
| 3 | TryParseJwt in set-variable | Parses the bearer value without validating it and reads tid into jwt-tid. | Missing or unparseable tid is traced and returns 401. |
| 4 | set-variable | Builds the tenant-validation URL, cache key, and Ontinue-tenant flag. | Subsequent tenant processing fails closed. |
| 5 | cache-lookup-value | For a non-Ontinue tenant, checks cached active status. | A miss invokes tenant validation. |
| 6 | send-request with HEAD | On a cache miss, calls the tenant-validation API using the APIM managed identity. | Request failure enters on-error; non-200 status becomes inactive. |
| 7 | cache-store-value | Caches the Boolean result for the configured duration. | Missing/false status returns a traced 401. |
| 8 | validate-jwt | Validates the bearer token against organizational and Ontinue OpenID metadata, environment audiences, tenant-bound issuers, signature, and lifetime. It stores the validated token as jwt. | APIM rejects the token and enters error processing. |
| 9 | choose claim checks | Requires roles and tid claims. | Each missing claim is traced and returns 401. |
| 10 | choose token-type check | Rejects idtyp=app for non-Ontinue tenants; customer traffic must be user traffic. | Traced 401. |
| 11 | set-header | Overwrites X-Tenant-Id with tid from the validated JWT. | Request does not proceed with an untrusted tenant header. |
| 12 | set-header | Leaves the original Authorization in place at global scope and copies it to X-Authorization if that header is absent. | No local rejection. API policy later replaces Authorization for the backend. |
| 13 | set-header | Overwrites Forwarded with original scheme, host, and path. | No local rejection. |
| 14 | include-fragment | Invokes the request trace fragment. | Fragment failure enters on-error. |
Tenant activation sub-flow
The deployed tenant lookup is skipped for the Ontinue tenant. Every other tenant uses a cache-first validation call:
<cache-lookup-value
key="@(context.Variables.GetValueOrDefault<string>("jwt-tid-cache-key", "NIL"))"
variable-name="jwt-tid-cache-value" />
<choose>
<when condition="@(!context.Variables.ContainsKey("jwt-tid-cache-value"))">
<send-request
mode="new"
response-variable-name="tenant-state"
timeout="20"
ignore-error="false">
<set-url>@(context.Variables.GetValueOrDefault<string>("tenant-validation-url", "NIL"))</set-url>
<set-method>HEAD</set-method>
<authentication-managed-identity
resource="{{APIM-TENANT-VALIDATION-AUDIENCE}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
ignore-error="false" />
</send-request>
<set-variable
name="jwt-tid-cache-value"
value="@(((IResponse)context.Variables["tenant-state"]).StatusCode == 200)" />
<cache-store-value
key="@(context.Variables.GetValueOrDefault<string>("jwt-tid-cache-key", "NIL"))"
value="@((bool)context.Variables["jwt-tid-cache-value"])"
duration="{{APIM-TENANT-CACHE-DURATION}}" />
</when>
</choose>
Only HTTP 200 means active. Unknown, inactive, or unavailable tenant state must
not silently become authorized. The cache duration bounds how quickly customer
offboarding takes effect at this layer.
JWT validation
The real policy contains an environment-specific audience list. The sanitized shape is:
<validate-jwt
header-name="Authorization"
require-scheme="Bearer"
require-signed-tokens="true"
output-token-variable-name="jwt">
<openid-config url="https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration" />
<openid-config url="{{APIM-ONTINUE-OPENID-CONFIGURATION-URL}}" />
<audiences>
<audience>{{APIM-PORTAL-API-AUDIENCE}}</audience>
<audience>{{APIM-INTERNAL-API-AUDIENCE}}</audience>
<audience>{{APIM-APPROVED-INTEGRATION-AUDIENCE}}</audience>
</audiences>
<issuers>
<issuer>{{APIM-ONTINUE-V1-ISSUER}}</issuer>
<issuer>{{APIM-CALLER-TENANT-V1-ISSUER}}</issuer>
<issuer>{{APIM-ONTINUE-V2-ISSUER}}</issuer>
<issuer>{{APIM-CALLER-TENANT-V2-ISSUER}}</issuer>
</issuers>
</validate-jwt>
Global policy checks that a roles claim exists; operation policy decides which
Ion.* role authorizes a route. Possessing any role is therefore not sufficient
to invoke any operation.
Headers after global inbound policy
| Header | Deployed source | Trust and use |
|---|---|---|
Authorization | Original caller bearer token | Validated at global scope. A normal API policy later overrides it with an APIM UAMI token for backend OAuth. |
X-Authorization | Copy of original caller bearer token | Sensitive compatibility channel for approved BFF routes. It must not be logged, stored, or propagated beyond the user-token termination boundary. |
X-Tenant-Id | tid from the validated JWT | Trusted gateway-derived tenant context. The backend must still enforce its customer and operation rules. |
X-Transaction-Id | Caller value or generated value | End-to-end correlation. Services propagate it to dependent calls. |
Forwarded | Original scheme, host, and path | Routing context; not an authorization grant. |
The global policy uses exists-action="skip" for X-Authorization. Consequently,
a caller-supplied X-Authorization is not overwritten. This is a security risk:
the target design must delete or override untrusted inbound values before setting
a gateway-owned original-token header.
Relationship to API and operation policy
After global inbound completes, inherited service policy executes:
- API policy selects the backend and applies API-level rate limits.
- API policy obtains a token using an approved APIM UAMI.
- API policy overrides backend
Authorizationwith the APIM token. - Operation policy rewrites the URI and requires the operation’s
Ion.*role. - The inherited global backend section forwards the request.
The original caller token and backend token have different purposes. The first authorizes caller-to-APIM access. The second authenticates APIM to the OAuth-protected compute resource.
Backend, outbound, and error sections
The deployed backend section isolates concurrency by context.Api.Id, emits a
trace containing backend URL, API ID, and operation ID, and forwards with a
120-second timeout:
<backend>
<limit-concurrency key="@(context.Api.Id)" max-count="${environment_concurrency}">
<trace source="ION Platform API Request" severity="information">
<message>ION Platform APIM Concurrency Request</message>
<metadata name="BackendEndpointUri" value="@(context.Request.Url.ToString())" />
<metadata name="ApiId" value="@(context.Api.Id)" />
<metadata name="OperationId" value="@(context.Operation.Id)" />
</trace>
<forward-request timeout="120" fail-on-error-status-code="true" />
</limit-concurrency>
</backend>
fail-on-error-status-code="true" routes backend 4xx and 5xx responses
through APIM error processing. The outbound section invokes
fragment-response-trace; the on-error section invokes
fragment-error-trace.
Trace fragments: deployed behavior and required target
The fragments are installed before global policy because the global policy references them by ID.
| Fragment | Deployed behavior | Required safe target behavior |
|---|---|---|
| Request | Uses existing jwt, or parses X-Authorization before Authorization. Logs correlation/request IDs, selected user/token claims, all non-auth request headers, original URI, and the full request body. | Log bounded route, correlation, outcome, and timing metadata. Do not log raw claims, broad headers, or request bodies by default. |
| Response | If jwt is absent, attempts token parsing. Logs non-auth response headers, rate-limit counters, status/reason, and the full response body. | Log bounded status, timing, cache, and rate-limit metadata. Do not log response bodies or broad headers by default. |
| Error | Logs extensive identity claims and roles when available, request and response headers, rate-limit values, URLs, full response body, and serialized APIM error details. | Log a stable error category, policy location, status, route, and correlation ID. Minimize identity and exception detail and never emit customer payloads. |
The response fragment’s fallback currently reads X-Authorization and then, when
that value is not NIL, replaces it with Authorization. This inverted fallback
can select the backend APIM token instead of the preserved caller token. It is an
implementation defect, not a pattern to reproduce.
The current trace fragments exclude Authorization and X-Authorization from
their header dumps, but their broad identity and body capture is still unsafe for
a shared customer platform. The deployed behavior is tracked as a discrepancy;
new policies MUST follow the minimized trace example in Policy
authoring.
Public health bypass
Policy inheritance depends on <base />. The public GET and HEAD health
operation policies deliberately omit it from inbound, apply an IP rate limit,
and return a synthetic response without calling a backend.
<inbound>
<rate-limit-by-key
calls="200"
renewal-period="60"
counter-key="@(context.Request.IpAddress)" />
<return-response>
<set-status code="200" reason="OK" />
<set-body>{ "status": "Healthy" }</set-body>
</return-response>
</inbound>
Authenticated health includes <base />, applies per-IP and per-tenant limits,
requires Ion.Health.Read, and returns a synthetic result. Neither operation
proves backend readiness. The other reviewed exception is the dedicated Phoenix
webhook flow, which bypasses global inbound authentication but
retains global backend, outbound, and error inheritance and validates Microsoft
Graph notifications in application code. No ordinary protected operation may
omit global inbound inheritance.
Known implementation risks
| Risk | Current implementation | Required disposition |
|---|---|---|
| Concurrency configuration drift | Terraform supplies 20; XML hard-codes 30 or 200. | Make one configuration source authoritative and test rendered policy. |
| Unvalidated tenant pre-routing | tid is parsed before JWT validation to select tenant status. | Constrain destination construction, validate format, and keep authorization dependent on validated JWT. |
| Caller-controlled original-token header | X-Authorization uses exists-action="skip". | Delete or override any inbound value before creating gateway-owned context. |
| Original token copied broadly | Global policy creates X-Authorization for inherited routes. | Restrict original-token preservation to approved user-context BFF routes. |
| Excessive trace data | Fragments capture bodies, claims, roles, and broad headers. | Replace with bounded, redacted telemetry and controlled sampling. |
| Response trace fallback | Inverted condition can choose the wrong authorization token for parsing. | Correct the condition or remove token parsing from response tracing. |
| Large global audience catalogue | One global list accepts several application audiences. | Keep lists environment-controlled and pair every route with explicit operation authorization and approved caller rules. |
These findings describe deployed behavior; they do not relax the normative API Management Guidelines.
Validation checklist
For each environment, verify:
- missing
Authorizationreturns401; - malformed tokens and tokens without
tidfail closed; - inactive, unknown, and unavailable customer tenants are denied;
- valid Ontinue tokens skip customer-tenant lookup;
- signature, lifetime, issuer, and environment audience are validated;
- missing
rolesandtidclaims are denied; - external-tenant application tokens are denied;
X-Tenant-Idcomes only from the validated token;- caller-supplied trusted-context headers cannot survive unchanged;
- every protected API and operation inherits global policy;
- operation policy requires the intended
Ion.*role; - API policy replaces backend
Authorizationwith the expected APIM UAMI token; - concurrency and timeout match the approved environment configuration;
- public health alone bypasses global inbound authentication; and
- traces contain no bearer tokens, customer payloads, unnecessary identity data, or unrestricted exception details.