APIM Webhook Flow Implementation
External webhook providers cannot 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.
V3 has two deployed webhook APIs:
| Webhook | Provider proof | Edge check at APIM | Source |
|---|---|---|---|
| Phoenix Microsoft Graph (carried over from V2) | Validation challenge, payload validation JWTs, clientState, tenant, subscription ID | None | phoenix/api/policies/apim-phoenix-graph-webhook-api-policy.xml, phoenix/infrastructure/phoenix_webhooks_api.tf |
| Pigeon Twilio | X-Twilio-Signature (HMAC over URL and parameters) | X-Azure-FDID must match {{APIM-FRONT-DOOR-ID}} | pigeon/infrastructure/policies-twilio-webhooks/apim-api-policy.xml, pigeon/infrastructure/main-twilio-webhooks-apim.tf |
Neither exception is an unauthenticated-backend pattern. APIM still authenticates to the OAuth-protected Function App with its managed identity, while the application validates the provider’s proof.
Why the webhook bypass exists
The normal global inbound policy requires an Authorization bearer token,
validates its tenant and audience, and requires role claims. Webhook providers
use a different proof model, so the dedicated webhook APIs do not inherit normal
caller JWT validation. This exception MUST remain limited to operations whose
provider validation is implemented and tested in application code.
Exact policy-inheritance behavior
Both webhook APIs bypass only global inbound policy. Global backend, outbound, and error sections still run.
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; - no global
Forwardedheader or request trace (each API supplies its own); and - no future global
X-Azure-FDIDcheck. When APIM-02 is fixed globally, each webhook API keeps its own check, as Pigeon does today. Phoenix needs one added.
The inherited global backend still applies per-API concurrency and the bounded
forward-request. Global response and error fragments still execute.
Webhook exception path
For Phoenix, the X-Azure-FDID and proof-header checks are absent, so the flow
goes straight from the API inbound to the rate limit.
Pigeon Twilio webhook
APIM configuration
Verified in pigeon/infrastructure/main-twilio-webhooks-apim.tf:
| Item | Value |
|---|---|
| API path | pig-ext-twilio |
| Product | apim-product-pigeonexttwilio-{env}-{loc}-01 |
| Backend | CustomerContact Function App |
| Contract | pigeon/api/pigeon_twilio_webhooks_api.yaml |
| Operation ID | Public path | Backend rewrite | Contract details |
|---|---|---|---|
post-webhook-twilio-call-received-v1 | POST /v1/webhooks/twilio/call-received | /v1/webhooks/twilio/call-received | Form-urlencoded Twilio Voice parameters; 200 returns TwiML (application/xml) |
post-webhook-twilio-call-initiated-v1 | POST /v1/webhooks/twilio/call-initiated | /v1/webhooks/twilio/call-initiated | Also requires query metadata incident_number, severity, title, ion_workspace_id, ion_security_incident_id, campaign_id; 200 returns TwiML |
post-webhook-twilio-outbound-call-status-events-v1 | POST /v1/webhooks/twilio/outbound-call-status-events | /v1/webhooks/twilio/outbound-call-status-events | Same query metadata as call-initiated; 200 OK |
The contract declares a BearerAuth scheme component but does not attach it to
these operations; each operation instead requires X-Twilio-Signature. This
correctly describes the effective trust model. Removing the unused component
would avoid confusion.
Deployed API policy
<policies>
<inbound>
<!-- Intentionally no inbound base: Twilio cannot present an ION token. -->
<check-header name="X-Azure-FDID" failed-check-httpcode="403"
failed-check-error-message="Invalid request. The webhook is not routed through the front door."
ignore-case="false">
<value>{{APIM-FRONT-DOOR-ID}}</value>
</check-header>
<check-header name="X-Twilio-Signature" failed-check-httpcode="401"
failed-check-error-message="Not authorized request. The webhook request is missing the X-Twilio-Signature header."
ignore-case="false" />
<set-backend-service base-url="${globals.backend_base_url}" />
<set-variable name="twilioWebhooksLimitCounterKey"
value="@(context.Api.Id + "-" + context.Request.IpAddress)" />
<rate-limit-by-key calls="100" renewal-period="60"
counter-key="@(context.Variables.GetValueOrDefault<string>("twilioWebhooksLimitCounterKey", "none"))"
increment-condition="@(context.Response.StatusCode >= 200 && context.Response.StatusCode < 400)"
remaining-calls-variable-name="twilioWebhooksRemainingCallsPerIp"
remaining-calls-header-name="X-RateLimit-Twilio-Webhooks-Remaining-Ip" />
<!-- trace of rate-limit counters omitted -->
<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" /> <!-- APIM-03: logs form body -->
<authentication-managed-identity
resource="{{APIM-AZURE-AD-APPLICATION-ID}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
output-token-variable-name="msi-access-token"
ignore-error="false" />
<set-header name="Authorization" exists-action="override">
<value>@("Bearer " + (string)context.Variables["msi-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 operation policy calls <base /> and rewrites the URI only.
At APIM, the X-Twilio-Signature check verifies only that the header is
present. The cryptographic check happens in the application. The rate limit is
keyed on API and source IP and counts successful responses; it is not proof that
the sender is Twilio.
Signature validation in the handler
Verified in
pigeon/app/Ontinue.Ion.Pigeon.CustomerContactFunc/Startup/Twilio/TwilioSignatureValidationMiddleware.cs:
- The middleware validates with the Twilio SDK
RequestValidatorand the auth token fromTwilioConfig.AuthToken. Inferred: the token is sourced from App Configuration or Key Vault. - It is registered with
UseWhenfor exactly the three webhook function names (MiddlewareInitializer.cs). Those functions are marked.Unprotected(...)in the ION authentication middleware (ServiceInitializer.cs), so this middleware is their only sender check. - It throws
UnauthorizedAccessExceptionwhen the signature is missing or invalid (fail closed). - It rebuilds the public URL from
X-Forwarded-HostandX-Forwarded-Protoand strips the/apiprefix. Without those headers it falls back to the request URL, which then fails validation. - Tests:
TwilioSignatureValidationMiddlewareTests.cs.
Inferred: Front Door sets the forwarded headers. The code does not enforce that
they came from the trusted edge. Forging them still requires a valid HMAC for the
forged URL, which needs the auth token, so the risk is low. The APIM X-Azure-FDID
check also limits who can reach the handler.
Phoenix Microsoft Graph webhook
The Phoenix flow is unchanged from V2. Graph uses three proofs:
- an endpoint-ownership challenge: a
validationTokenquery value that the endpoint returns as plain text; - Graph-issued validation JWTs in resource-data notification payloads; and
- the subscription’s
clientState, tenant or organization ID, and subscription ID on every notification.
Deployed API policy
The policy matches the V2 page: no inbound <base />, backend selection, a
500-per-minute IP rate limit, Forwarded override, fragment-request-trace, and
APIM UAMI token acquisition that overrides Authorization. It has no
X-Azure-FDID check.
<inbound>
<!-- Intentionally no inbound base. No X-Azure-FDID check (APIM-02). -->
<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">...</set-header>
<include-fragment fragment-id="fragment-request-trace" /> <!-- APIM-03 -->
<authentication-managed-identity
resource="{{APIM-AZURE-AD-APPLICATION-ID}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
output-token-variable-name="msi-access-token"
ignore-error="false" />
<set-header name="Authorization" exists-action="override">...</set-header>
</inbound>
| Public operation | Backend rewrite |
|---|---|
POST /v1/subscriptions/webhooks/lifecycle | /v1/subscriptions/webhooks/lifecycle |
POST /v1/subscriptions/webhooks/resource | /v1/subscriptions/notifications/resource-change |
Application validation
- Challenge: when
validationTokenis present, both handlers return it with200andtext/plain. The handlers also log the token (Verified inResourceNotificationHandlerFunc.csandLifeCycleNotificationHandlerFunc.cs). - Resource-data notifications: Phoenix validates each payload JWT against the
configured tenant and client audience, then checks tenant,
clientState, and subscription ID before queuing.JwtTokenValidator.AreTokensValidreturnstruefor an empty token list (Verified), which weakens this path. - Lifecycle notifications: validated by
organizationId(falling back totenantId), expected tenant,clientState, and a non-empty subscription ID. Invalid notifications are discarded; the handler returns202. - Middleware: the two webhook functions are excluded from the normal authentication and authorization middleware, so handler validation is mandatory for them.
The full Phoenix walkthrough, including code samples, remains in the V2 webhook flow.
Required webhook guardrails
A webhook API that bypasses global inbound policy MUST:
- use a dedicated external API, product, and explicit operation-policy map;
- omit inbound
<base />only at the reviewed API boundary; - check
X-Azure-FDIDagainst{{APIM-FRONT-DOOR-ID}}at API scope; - check that the provider’s proof header is present at API scope where the provider uses one;
- document the provider’s challenge and notification-authentication protocol;
- validate provider signatures, JWTs, shared state, or equivalent cryptographic proof in the application before trusting the payload, using the provider’s supported library;
- rebuild any URL used in signature validation only from trusted edge headers;
- 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;
- handle provider retries idempotently, for example keyed on Twilio
CallSid; - acknowledge only after validation and durable acceptance required by the provider protocol;
- not include body-logging fragments such as
fragment-request-trace, or use a redacting variant; - avoid logging validation tokens, payload JWTs, signatures,
clientState, provider secrets, complete bodies, phone numbers, or authorization headers; and - include negative tests proving the 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 | Webhook | Deployed behavior | Required disposition | Status |
|---|---|---|---|---|
| No edge check (APIM-02) | Phoenix | No X-Azure-FDID check; the API is reachable directly on the APIM gateway. | Add the same check-header as Pigeon. | Open |
| Full-body APIM tracing (APIM-03) | Both | fragment-request-trace logs the full body: Graph notifications, and Twilio form data including caller and callee phone numbers. | Remove the fragment or use a bounded, redacting webhook fragment. | Open |
| No transaction-ID creation | Both | Webhook API inbound does not set X-Transaction-Id. | Create a gateway correlation ID at API scope. | Open |
| Validation challenge logging | Phoenix | Both handlers log validationToken. | Remove token values from logs. | Open |
| Empty validation-token collection | Phoenix | Resource token validation succeeds when the list is empty. | Require at least one valid token for resource-data notifications. | Open |
| OpenAPI security mismatch | Phoenix | The contract declares BearerAuth while APIM performs no caller bearer validation. | Model the provider security semantics. | Open |
| Unused bearer component | Pigeon | BearerAuth is declared but not attached. | Remove it to avoid confusion. | Low, open |
| Forwarded-header trust | Pigeon | URL rebuilt from X-Forwarded-* without checking origin; mitigated by HMAC and the FDID check. | Document as accepted, or restrict to known edge hosts. | Low, open |
| Broad webhook exception | Both | Normal middleware is skipped by function-name classification. | Keep the allow-list minimal and require sender-validation tests for every entry. | Ongoing |
Validation checklist
- A request without the expected
X-Azure-FDIDis rejected with403(Pigeon today; Phoenix after APIM-02). - A Twilio request without
X-Twilio-Signatureis rejected with401at APIM. - A Twilio request with an invalid signature, or a valid signature for a different URL or parameter set, is rejected by the middleware.
- A Graph endpoint-validation request receives the exact token as
text/plainwithout exposing it in logs. - Webhook requests do not require an ION caller bearer token and do not execute global inbound JWT or tenant policy.
- API policy acquires the expected APIM UAMI token and overrides backend
Authorization. - Direct anonymous calls to either Function App are rejected by platform OAuth.
- Global backend concurrency and forwarding still execute.
- Resource-data notifications without validation JWTs are rejected.
- Wrong tenant,
clientState, or missing subscription ID is not queued. - Duplicate provider delivery does not duplicate non-idempotent business effects.
- Request-size and rate-limit behavior is tested.
- No webhook token, signature,
clientState, phone number, or full payload appears in APIM or application logs. - Removing webhook-specific validation causes security tests to fail.