A re-runnable script and CI job that applies a pinned policy baseline (Client ID Enforcement 1.3.3 and Spike Control 1.2.2 at 100 requests per second with a queue of 25) to every Production API in an Anypoint org through the Anypoint Platform REST APIs. Covers the API inventory map, why a naive re-run can duplicate or silently skip policies, the GET-before-POST hardening, connected-app credentials, drift detection, and troubleshooting. Drawn from an energy and industrial API estate; applicable to any industry.
Tags: anypoint-platform, automation, api-security, client-id-enforcement, idempotency, devops, api-governance, api-manager, spike-control, rate-limiting, ci-cd, custom-policy
Production API Governance Baseline: Idempotent Policy Automation for Anypoint API Manager
Deliverable: A single re-runnable shell script, plus the CI job around it, that applies Client ID Enforcement and Spike Control to every registered Production API in an Anypoint org through the Anypoint Platform REST APIs, so no production API ships, or is promoted, without the baseline.
Objective: In most orgs the policy baseline lives in a wiki page and in someone's memory. A new API gets promoted to Production, nobody opens API Manager, and it serves traffic with no client authentication and no throttle. For energy, utility and industrial platforms that expose sensor, scheduling and nomination data, that is an unauthenticated path to operational systems. Clicking through the console per API does not scale and cannot be audited. Working looks like this: the baseline is code, one command brings every production API to the same state, and running it twice changes nothing the second time, so it is safe to schedule in CI.
What's Getting Built
- Authentication (Anypoint access management) — exchanges a service user's credentials for a bearer token used on every later call ·
POST /accounts/login
- API Manager policy applier (Anypoint API Manager, per API instance) — attaches a policy to one managed API instance in one environment. Call it twice per API: Client ID Enforcement (
client-id-enforcement 1.3.3) and Spike Control (spike-control 1.2.2) · POST /apimanager/api/v1/organizations/{orgId}/environments/{envId}/apis/{apiInstanceId}/policies
- Policy state check (Anypoint API Manager) — read the current policies before writing, so "already applied" is detected rather than inferred from an error ·
GET /apimanager/api/v1/organizations/{orgId}/environments/{envId}/apis/{apiInstanceId}/policies
- API inventory map (automation configuration) — an explicit, reviewed map of API Manager instance IDs to human-readable labels. The reference estate has seven Production APIs: sensor data (v2 and a deprecated v1), energy-efficiency enrollment, pipeline nominations, payments, scheduling and customer 360.
Prerequisites
- An Anypoint Platform user (ideally a dedicated service identity) with permission to manage policies in the Production environment of API Manager. Username and password work, but we recommend a connected app with client credentials and a scoped role instead, so the secret can be rotated and is not a human login.
- The org ID, the Production environment ID, and the group ID that owns the MuleSoft-published policy assets (it goes in each policy payload as
groupId). Treat all three as inputs, never as committed constants.
- API Manager instance IDs for each API, taken from the API Manager list for the Production environment. These are the numeric IDs used in the URL, not Exchange asset names.
- Each API already registered in API Manager (managed by a Mule gateway or proxy). Policies cannot be attached to something API Manager does not know about.
- Agreement with API owners on the baseline values (rate and queue depth), because a throttle set too tight is an outage you caused. Get this signed off before the first production run; it often takes longer than writing the automation.
bash 4 or later if you use an associative array for the inventory (the macOS default bash 3.2 does not support it), plus curl and python3 on the runner.
- A secret store for CI (not the repo) holding the Anypoint credentials, injected as environment variables.
Architecture
1. Define the baseline as data
- Pin exactly two policies and their versions:
client-id-enforcement at 1.3.3 and spike-control at 1.2.2. Pinning matters: an unpinned "latest" would change enforcement behaviour on a re-run without anyone reviewing it.
- Client ID Enforcement configuration:
credentialsOriginHasHttpBasicAuthenticationHeader set to customExpression, clientIdExpression set to #[attributes.headers['client_id']], and clientSecretExpression set to #[attributes.headers['client_secret']]. Consumers send credentials as client_id and client_secret headers. Decide deliberately whether that is your convention; HTTP Basic is the other common one.
- Spike Control configuration:
maximumRequests 100 per timePeriodInMilliseconds 1000 (100 requests per second), queuingLimit 25, delayTimeInMillis 1000, delayAttempts 1, exposeHeaders true. Excess requests queue up to 25 deep and retry once after a second; beyond that they are rejected. exposeHeaders lets well-behaved clients back off based on the response headers.
- Send
pointcutData as null so the policy applies to every resource and method of the API, not a subset.
2. Keep the API inventory explicit
- Maintain the map of API Manager instance ID to label in one reviewed place. Include a deprecated version that is still deployed (the reference estate has a v1 sensor API): a deprecated API that is still reachable is still an attack surface, so it gets the same baseline until it is actually undeployed.
- Do not rely on a hand-edited list alone. A newly promoted API is unprotected until someone remembers to add it. Enumerate the Production environment's APIs from API Manager on every run, and fail the build when it finds an instance that is neither in the reviewed list nor explicitly exempted.
3. Authenticate once per run
- Call
POST /accounts/login with the username and password as a JSON body and read access_token from the response. Reuse the one token for the whole run and send it as Authorization: Bearer {token}.
- Read credentials from
ANYPOINT_USER and ANYPOINT_PASS environment variables only, and run with set -euo pipefail so an unset variable aborts the run instead of sending an empty login.
- Recommendation: replace the username and password with a connected app's client credentials grant, scoped to API Manager policy management in the Production environment only.
4. Apply each policy to each API
- For every instance,
GET its policies and compare by policy assetId, assetVersion and configuration against the baseline. POST the policy document (configurationData, assetId, assetVersion, groupId, pointcutData) only when it is absent or different.
- Isolate failures per call: a failure on one policy or one API is recorded and the loop continues, so one broken API does not block the rest. Record the failure; do not swallow it.
- Don't treat any non-2xx as "already applied". A
curl -sf style wrapper exits non-zero on every HTTP error and hides the response body, so an expired token, a wrong instance ID and a permissions failure all look identical to a duplicate-policy rejection, and a log full of [SKIP] reads as success. Capture the status code and body instead.
- Report three outcomes separately: applied, already compliant, failed. Exit non-zero if any call failed, so CI turns red.
- Relying on the platform to reject a repeat
POST is a convention, not a verified state. Whether a second POST of an attached policy is rejected or attaches a duplicate is something to prove in a sandbox, not assume.
5. Wire it into CI
- Run on a schedule and on merge to the branch that holds the inventory map. A scheduled run is what catches a policy someone removed by hand in the console.
- Inject
ANYPOINT_USER and ANYPOINT_PASS (or connected app credentials) from the CI secret store. Never echo the login payload or token to the job log.
- Use a dry-run mode (read-only
GETs, report the drift, change nothing) for pull requests, and the applying mode only on the protected branch.
6. Security and compliance
- The baseline answers two common control families: authentication of API consumers (Client ID Enforcement) and availability protection against bursts and runaway clients (Spike Control). For operational-technology-adjacent data such as pipeline nominations and sensor readings, map these to your NERC CIP or internal OT policy controls as evidence, with your compliance owner.
- Client ID Enforcement checks that a consumer holds a registered contract; it does not encrypt anything. TLS to the gateway and network-level controls remain separate.
- Credentials: environment variables or a CI secret store only; no literal values in the repo or the job output. Keep org, environment and group identifiers in configuration, not hardcoded in a shared repository.
- Audit: the run log (API label, policy, applied, compliant or failed) is the run record. Keep CI logs, and record which commit and which service identity produced each change. API Manager's own audit log is the authoritative record of what was applied.
- Least privilege: the identity running this needs policy management on Production only, not org administration.
Sample payload — Spike Control request body
{
"configurationData": {
"maximumRequests": 100,
"timePeriodInMilliseconds": 1000,
"delayTimeInMillis": 1000,
"delayAttempts": 1,
"queuingLimit": 25,
"exposeHeaders": true
},
"assetId": "spike-control",
"assetVersion": "1.2.2",
"groupId": "{mulesoft_policy_group_id}",
"pointcutData": null
}
Sent to POST /apimanager/api/v1/organizations/{orgId}/environments/{envId}/apis/{apiInstanceId}/policies. The Client ID Enforcement body has the same envelope with assetId client-id-enforcement, assetVersion 1.3.3 and the three expression fields shown in step 1.
Deterministic checks
- Each of the two policy calls is a
POST to .../apis/{apiInstanceId}/policies with a bearer token, JSON body, and the exact assetId and assetVersion pair above. A request with a different version is a defect.
- Re-running against a fully compliant environment leaves the policy count per API unchanged: exactly one
client-id-enforcement and one spike-control per instance, never two of either.
- A failure on one API (or one policy) does not stop processing of the remaining APIs, and the run's overall exit status reflects it.
- No credential, token or Anypoint ID appears in the committed code, the CI log, or the job output.
- The automated proof: a CI job that runs the automation against a non-production environment twice, then reads back the policies with
GET and asserts the counts, versions and configuration values.
Testing and validation
- Happy path: against a sandbox API instance with no policies, run the automation and confirm both policies appear in API Manager with the configured values. Send a request without
client_id/client_secret headers and confirm it is rejected; with valid contract credentials confirm it passes.
- Throttle behaviour: send a burst above 100 requests in one second and confirm requests queue and then reject beyond the queue of 25, with the rate-limit headers present because
exposeHeaders is true.
- Edge case that breaks a naive implementation: re-applying. A policy POST for an asset already attached may be rejected or may attach a second copy, depending on the platform. Test it once in a sandbox and read back the policy list.
- Second edge case: an API instance ID from another environment returns an error. If errors are swallowed as skips, a typo looks like "already protected". Validate every ID in the map against the target environment before applying.
- Third: the deprecated API must be either covered or explicitly exempted in the inventory with a reason.
- Mapping correctness: compare the read-back configuration to the baseline values field by field, not only the policy name.
Phased rollout
Phase 1 — Connect
- Authenticate with the service identity against a sandbox environment and list API instances. Confirm the identity can read and write policies there, and nowhere else.
Phase 2 — Map and validate
- Build the inventory map from the real API Manager list. Agree the rate and queue values with each API owner. Apply in sandbox, run twice, read back, and confirm the
GET-before-POST check and the applied, compliant and failed reporting behave as expected.
Phase 3 — Production
- Run in dry-run mode against Production first and review the drift report. Apply during a quiet window, API by API for the first run, and watch error rates, because Client ID Enforcement will reject existing consumers that do not hold a contract. Then schedule the job and hand ownership to the platform team.
Success metrics
- Percentage of Production API instances carrying both baseline policies at the pinned versions (target all of them; measure from API Manager, not from the run log).
- Number of Production APIs promoted with no baseline, and time from promotion to compliance. Run frequency sets the upper bound.
- Policy drift events found by scheduled runs (a policy removed or altered by hand).
- Platform signals after rollout: 401/403 rate from Client ID Enforcement (unregistered consumers surfacing), rejected and queued request counts from Spike Control (limits set too low), and gateway latency. Record a pre-rollout baseline first so the change is measurable.
Troubleshooting
- Every API reports a skip or failure on a first run — Likely cause: the token is invalid or the login failed, or the identity lacks policy permission, and error output is being hidden. Fix: run the login call by hand, check the token, and rerun one policy
POST with -v and without -f to see the status and message.
declare: -A: invalid option — Likely cause: bash 3.2 (the macOS default) running a script that uses an associative array. Fix: run with bash 4 or later, or use a container image in CI.
- A policy fails on the first run for one API only — Likely cause: wrong instance ID, an instance in another environment, or the policy already attached manually. Fix: verify the ID in the Production API Manager list and read the API's current policies.
- Authentication fails outright — Likely cause:
ANYPOINT_USER or ANYPOINT_PASS unset (the run aborts under set -u), a rotated password, or MFA/SSO on a human account. Fix: use a service identity or connected app.
- Consumers suddenly get 401 after rollout — Likely cause: Client ID Enforcement now requires a registered contract and the
client_id/client_secret headers. Fix: have consumers request access in Exchange, or confirm the header names match the expression.
- Legitimate traffic gets queued or rejected — Likely cause: 100 requests per second and a queue of 25 are too low for that API. Fix: raise the values for that API after measuring peak traffic, and keep the exception in the inventory, not as a console edit.
- A new API is unprotected — Likely cause: the inventory was not updated at promotion. Fix: add the instance ID, or enumerate APIs from API Manager and fail CI on unknown ones.