APIM Webhook Flow Implementation
External webhook providers cannot always present an ION Entra access token. ION therefore supports an explicit webhook exception in which a dedicated API omits global inbound policy inheritance and delegates sender-specific validation to the webhook implementation.
This page documents the deployed Phoenix Microsoft Graph webhook flow from:
phoenix/infrastructure/phoenix_webhooks_api.tf;phoenix/api/specs/openapi_webhooks.yaml;phoenix/api/policies/apim-phoenix-graph-webhook-api-policy.xml;- the lifecycle and resource operation-policy files; and
- the Phoenix webhook handlers and notification service.
This exception is not an unauthenticated-backend pattern. APIM still authenticates to the OAuth-protected Function App using its managed identity, while Phoenix validates the Graph notification at the application layer.
Why the webhook bypass exists
The normal global inbound policy requires an Authorization bearer token,
validates its tenant and audience, and requires role claims. Microsoft Graph
webhook delivery uses a different proof model:
- Graph validates endpoint ownership by sending a
validationTokenquery value that the endpoint must return as plain text. - Resource-data notifications contain Graph-issued validation JWTs in the payload.
- Notifications carry the subscription’s
clientState, tenant or organization identifier, and subscription identifier for application validation.
The dedicated external webhook API therefore does not inherit normal caller JWT validation. This exception MUST remain limited to operations whose provider validation is implemented and tested in application code.
Deployed end-to-end flow
There are two independent trust decisions:
| Boundary | Identity or proof | Enforcement |
|---|---|---|
| Graph → Phoenix webhook | Endpoint validation challenge, payload validation JWTs where supplied, expected tenant, clientState, and subscription ID | Phoenix webhook handlers and notification service |
| APIM → Phoenix Function App | APIM user-assigned managed-identity access token | Function App platform OAuth before function execution |
Exact policy-inheritance behavior
The webhook does not bypass every global section. It bypasses only global inbound authentication and tenant processing.
Consequences of omitting inbound <base /> at API scope include:
- no required caller
Authorizationheader; - no global transaction-ID creation;
- no pre-validation tenant lookup or customer allow-list check;
- no global caller JWT, issuer, audience, or role validation;
- no trusted
X-Tenant-IdorX-Authorizationcreation; and - no global
Forwardedheader or request trace—the API policy supplies its own forwarding header and trace invocation.
The inherited global backend still applies per-API concurrency and the bounded
forward-request. Global response and error fragments still execute.
Deployed API policy
The external Graph API policy deliberately has no <base /> in inbound. It
selects the Phoenix backend, rate-limits by source IP, sets forwarding context,
traces the request, acquires an APIM managed-identity token, and overwrites
Authorization before reaching the backend.
<policies>
<inbound>
<!-- Intentionally no inbound base: normal caller JWT policy is not applicable. -->
<set-backend-service base-url="${globals.backend_base_url}" />
<rate-limit-by-key
calls="500"
renewal-period="60"
counter-key="@(context.Request.IpAddress)"
increment-condition="@(context.Response.StatusCode >= 200 && context.Response.StatusCode < 400)"
remaining-calls-variable-name="remainingCallsPerIP" />
<set-header name="Forwarded" exists-action="override">
<value>@("proto=" + context.Request.OriginalUrl.Scheme + ";host=" + context.Request.OriginalUrl.Host + ";path=" + context.Request.OriginalUrl.Path + ";")</value>
</set-header>
<include-fragment fragment-id="fragment-request-trace" />
<authentication-managed-identity
resource="{{APIM-BACKEND-AUDIENCE}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
output-token-variable-name="backend-access-token"
ignore-error="false" />
<set-header name="Authorization" exists-action="override">
<value>@("Bearer " + (string)context.Variables["backend-access-token"])</value>
</set-header>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<set-header name="x-aspnet-version" exists-action="delete" />
<set-header name="x-powered-by" exists-action="delete" />
</outbound>
<on-error>
<base />
</on-error>
</policies>
The rate limit counts successful responses as deployed. It is not proof that the source is Microsoft Graph, and source IP must not be treated as the webhook’s primary authentication mechanism.
The request trace runs before APIM replaces Authorization. The deployed trace
fragment excludes authorization headers, but it logs the full request body. That
can expose Graph notification content and is not the safe target pattern. Webhook
telemetry must be reduced to bounded metadata.
Operation policies and route mapping
Both webhook operations inherit the webhook API policy and rewrite only their backend path:
| Public operation | Backend rewrite | Application handler |
|---|---|---|
POST /v1/subscriptions/webhooks/lifecycle | /v1/subscriptions/webhooks/lifecycle | Lifecycle notification handler |
POST /v1/subscriptions/webhooks/resource | /v1/subscriptions/notifications/resource-change | Resource-change notification handler |
<policies>
<inbound>
<base />
<rewrite-uri
template="${globals.webhook_backend_path}"
copy-unmatched-params="true" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Here, operation inbound <base /> invokes the API policy. Because the API policy
has no inbound <base />, inheritance stops before global inbound.
Endpoint-validation challenge
When validationToken is present in the query string, both handlers return its
value with HTTP 200 and Content-Type: text/plain:
var validationToken = request.GetQueryParamValue("validationToken");
if (validationToken is not null)
{
var response = request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain");
await response.WriteStringAsync(validationToken, cancellationToken);
return response;
}
This challenge proves control of the registered endpoint to Microsoft Graph. It does not authenticate arbitrary notification requests after subscription setup. The validation token is sensitive transient input and MUST NOT be logged; the deployed handlers currently log it and should be remediated.
Notification validation
For a normal delivery, Phoenix performs application validation after platform OAuth has authenticated APIM.
Resource-data notifications
Phoenix:
- Parses the request body as a Graph change-notification collection.
- Reads the collection’s
validationTokens. - Validates each supplied JWT against the configured tenant and client audience.
- Rejects token-validation failure.
- Validates each notification’s tenant,
clientState, and subscription ID. - Queues only valid notifications for downstream handling.
var validationTokens = GetValidationTokens(notificationCollection);
await ValidateTokens(validationTokens, expectedTenant, expectedClient);
foreach (var notification in notificationCollection.Value)
{
if (HasExpectedTenantClientStateAndSubscription(notification))
{
notificationQueue.Enqueue(notification);
}
}
The deployed token validator returns success for an empty token list. Because the resource-data path is intended to require validation JWTs, tests and future hardening must require at least one token rather than treating an empty collection as valid.
Lifecycle notifications
Graph lifecycle notifications do not follow the same payload-token path. Phoenix validates each notification using:
organizationIdfor lifecycle events, falling back totenantIdwhere applicable;- the configured expected tenant;
- the configured subscription
clientState; and - a non-empty subscription ID.
Invalid individual notifications are discarded and are not queued. The handler
returns 202 after accepted notifications are handed to the internal notification
handler.
Function middleware exception
The Phoenix Function triggers use AuthorizationLevel.Anonymous because Function
keys are not the trust mechanism. Function App platform OAuth authenticates APIM
before invocation.
Phoenix explicitly excludes the two webhook function names from its normal in-process authentication and role-authorization middleware:
app
.UseWhen<AuthenticationMiddleware>(IsHttpAndNotWebhook)
.UseWhen<AuthorizationMiddleware>(IsHttpAndNotWebhook)
.UseWhen<ExceptionHandlingMiddleware>(IsHttp)
.UseWhen<CorrelationIdMiddleware>(IsHttp)
.UseWhen<RequestResponseLoggingMiddleware>(IsHttp);
Webhook-specific validation in the handlers and notification service therefore becomes mandatory. Adding a new webhook function without adding equivalent sender validation creates an unauthenticated application path even if APIM-to-backend OAuth remains correctly configured.
Required webhook guardrails
A webhook API that bypasses global inbound policy MUST:
- use a dedicated external API and explicit operation-policy map;
- omit inbound
<base />only at the reviewed API or operation boundary; - document the provider’s challenge and notification-authentication protocol;
- validate provider signatures, JWTs, shared state, or equivalent cryptographic proof before trusting the payload;
- validate subscription, tenant/customer, event type, timestamp, and replay context where the provider supplies them;
- authenticate APIM to an OAuth-protected backend with a narrowly authorized UAMI;
- fail closed when provider validation data is absent, invalid, ambiguous, or unavailable;
- rate-limit and bound request size, processing time, and queue work;
- acknowledge only after validation and durable acceptance required by the provider protocol;
- avoid logging validation tokens, payload JWTs,
clientState, encrypted content, complete bodies, or authorization headers; and - include negative tests proving normal global-policy bypass cannot be applied to other API operations.
Source-IP filtering may be added as defense in depth when the provider publishes a reliable range, but it must not replace provider-level validation.
Current implementation risks
| Risk | Deployed behavior | Required disposition |
|---|---|---|
| OpenAPI security mismatch | The webhook contract declares BearerAuth, while APIM deliberately performs no caller bearer validation. | Model the actual provider security semantics so generated documentation does not claim a control that is absent. |
| Full-body APIM tracing | Request and error fragments can capture notification payloads. | Use bounded webhook metadata and prohibit payload capture by default. |
| Validation challenge logging | Both handlers log the validationToken. | Remove token values from logs. |
| Empty validation-token collection | Resource token validation succeeds when the list exists but is empty. | Require at least one valid token for resource-data notifications. |
| No global transaction-ID creation | Webhook API inbound does not set X-Transaction-Id. | Create a gateway correlation ID without importing normal JWT policy, or ensure an equivalent trusted correlation layer. |
| Broad webhook exception risk | Authentication and authorization middleware are skipped by function-name classification. | Keep the function allow-list minimal and require dedicated sender-validation tests for every entry. |
Validation checklist
- A Graph endpoint-validation request receives the exact token as
text/plainwithout exposing it in logs. - A webhook request does not require an ION caller bearer token.
- The webhook API does not execute global inbound JWT or tenant policy.
- API policy acquires the expected APIM UAMI token and overwrites backend
Authorization. - Direct anonymous calls to the Function App are rejected by platform OAuth.
- Global backend concurrency and forwarding still execute.
- Global outbound and error behavior still execute with safe telemetry.
- Resource-data notifications without validation JWTs are rejected.
- Invalid validation JWT signature, issuer, tenant, audience, or lifetime is rejected.
- Wrong tenant,
clientState, or missing subscription ID is not queued. - Valid lifecycle and resource notifications are durably handed off before
202. - Request-size and rate-limit behavior is tested.
- No webhook token,
clientState, encrypted content, or full payload appears in APIM or application logs. - Removing webhook-specific validation causes security tests to fail.