Guardrails and usage

external_metering

Integrates with an external metering service for pre-request balance checks and post-response token usage reporting.

Praxis AI Development (bcdcfdbcf963) 6 min read

Switching projects opens that project’s default documentation release.

Versions marked “overview” do not contain this page. Selecting one opens that version’s documentation overview.

On this page

Integrates with an external metering service for pre-request balance checks and post-response token usage reporting.

Configuration Notes

Tenant identity is resolved from the highest-trust source available: an AuthenticatedIdentity extension published by a policy/auth filter from a cryptographically verified token, then verified {prefix}* metadata written by an authentication filter, then the identity_header_guard filter’s namespaced {namespace}.{prefix}* metadata, then raw {prefix}* request headers. A higher tier always wins, so forged client headers can never override verified claims, and identity headers plus client credentials are always stripped before the request is forwarded. Both event types carry data.organization_id and data.cost_center from {prefix}organization-id and {prefix}cost-center. When absent, those fields are empty strings rather than invented defaults.

When no {prefix}model identity header names the model and model_to_provider mapped the request, balance checks and usage events use the client-facing model ID it recorded rather than the provider target. That filter buffers the request body, so its body pass completes before this filter’s request hook runs the balance check.

Usage events include the optional quota_value, quota_formula, quota_unit, and quota_status fields when PPE quota policy runs earlier in the response phase. quota_usage and quota_context preserve the exact normalized policy inputs, including missing-field presence flags, so the result can be audited and recomputed. Declare external_metering before policy, and policy before token_count, because response hooks run in reverse filter order. Quota fields are enforcement/audit data, never currency.

For a complete setup where the Praxis Policy Engine (policy filter) verifies a JWT and this filter meters on the resulting tier-0 AuthenticatedIdentity — no {prefix}* header involved — see the end-to-end example below (a gateway config plus the PPE policy document it loads). A metered request then carries only Authorization: Bearer <jwt>, and usage is billed to the token’s verified identity_username_claim within its identity_group_claim.

Configuration

FieldTypeRequiredDescription
metering_urlstringyesBase URL of the external metering service (required).
allow_private_endpointboolnoAllow the metering endpoint to resolve to non-public addresses (loopback, private, link-local). Defaults to false, so callouts are rejected before connecting unless the operator opts in. Cloud metadata, unspecified, and multicast addresses remain blocked.
timeout_secondsintegernoHTTP timeout in seconds for all metering calls.
feature_keystringnoEntitlement feature key used in balance check URL path.
sourcestringnoCloudEvents source field value.
providerstringnoStatic provider name attributed to emitted CloudEvents.
fail_openboolnoWhen true (default), requests proceed if the metering service is unavailable. When false, requests are rejected with 503.
identity_header_prefixstringnoPrefix for tenant identity headers to capture and strip. Expected headers: {prefix}username, {prefix}group, {prefix}subscription, {prefix}model, {prefix}organization-id, {prefix}cost-center.
identity_metadata_namespacestringnoMetadata namespace the identity_header_guard filter writes captured identity headers under. Must match that filter’s metadata_namespace setting when both run in one pipeline.
identity_username_claimstringnoCustom claim on a policy/auth filter’s verified identity (tier 0) to meter as the tenant username. When unset, the verified subject id is used. Only consulted when an upstream filter (e.g. the policy engine) published an AuthenticatedIdentity for the request.
identity_group_claimstringnoCustom claim on a policy/auth filter’s verified identity (tier 0) to meter as the tenant group. When unset, no group is taken from the verified identity.
default_usernamestringnoFallback username when no identity header is present. If set, requests without {prefix}username are still metered under this name. If unset, metering is skipped entirely.
default_modelstringnoFallback model name when no identity model header is present.
internal_auth_tokenCredentialSourcenoOptional internal bearer token for authenticating metering callouts (the balance check and the usage report). One of value | env_var | file, read through the shared [CredentialSource] core: bounded reads, restart-free file rotation (ideal for a Kubernetes projected Secret), and fail-closed publication. When omitted, callouts are sent unauthenticated (unchanged behavior).

Examples

Example 1

filter: external_metering
metering_url: "http://metering-service:8080"
timeout_seconds: 5
feature_key: "inference-tokens"
source: "ai-gateway"
provider: "openai"
fail_open: true
identity_header_prefix: "x-tenant-"
identity_metadata_namespace: "identity"
default_username: "anonymous"
default_model: "unknown"

Example 2

# This end-to-end example is TWO files: the gateway config and the PPE policy
# document it loads through `config_path`. Save each part under the filename in
# its banner. The policy engine verifies a bearer JWT and publishes an
# AuthenticatedIdentity; external_metering meters on it (tier 0), so no
# x-tenant-* header is ever involved and a metered request carries only
# `Authorization: Bearer <jwt>`.

# ===== gateway.yaml =====
# Run from a praxis-ai checkout:  cargo run -p praxis-ai-proxy -- -c gateway.yaml
listeners:
  - name: gateway
    address: "127.0.0.1:8080"
    filter_chains: [main]

filter_chains:
  - name: main
    filters:
      # Verify the JWT and publish the verified identity. Declared before
      # external_metering so the AuthenticatedIdentity exists when metering
      # resolves the tenant. This chain serves plain-HTTP inference (no MCP),
      # so the protocol-metadata gate is turned off.
      - filter: policy
        config_path: "policy.yaml"
        require_protocol_metadata: false
        # The issuer/JWKS callout is loopback in this local example; dev only.
        allow_private_idp: true

      - filter: router
        routes:
          - path_prefix: "/"
            cluster: inference

      # Balance check + usage reporting. Meter the verified `preferred_username`
      # claim as the tenant username (falling back to the verified subject id)
      # and the `organization` claim as the tenant group — tier 0, never a
      # forgeable x-tenant-* header. Declared before token_count so the
      # response hooks (which run in reverse) populate token.* first.
      - filter: external_metering
        metering_url: "http://127.0.0.1:9090"
        allow_private_endpoint: true
        feature_key: "inference-tokens"
        source: "ai-gateway"
        provider: "openai"
        fail_open: true
        identity_username_claim: "preferred_username"
        identity_group_claim: "organization"

      - filter: token_count
        provider: openai

      - filter: load_balancer
        clusters:
          - name: inference
            endpoints: ["127.0.0.1:3000"]

# Every upstream here is on loopback, so private endpoints must be opted in.
insecure_options:
  allow_private_endpoints: true

---

# ===== policy.yaml (loaded by the policy filter's config_path above) =====
# One identity/jwt plugin verifies the bearer token against a trusted issuer
# and publishes the AuthenticatedIdentity. `on_error: fail` makes a missing or
# invalid token reject the request; `global.authentication` runs the plugin on
# every route.
#
# `claim_mapper: standard` passes non-registered claims through to the
# identity's custom claims, so external_metering can read `preferred_username`
# and `organization`. A claim the standard mapper promotes to a typed field
# (e.g. `groups` -> teams) would NOT appear as a custom claim, so pick a
# passthrough claim such as `organization` for the tenant group.
plugins:
  - name: jwt-user
    kind: identity/jwt
    hooks: [identity.resolve]
    mode: sequential
    on_error: fail
    config:
      header: Authorization        # the "Bearer " prefix is stripped automatically
      claim_mapper: standard
      trusted_issuers:
        - issuer: "https://idp.example.com"
          audiences: ["ai-gateway"]
          algorithms: ["HS256"]     # production: RS256 with a jwks_url decoding_key
          decoding_key:
            kind: secret
            secret: "REPLACE-WITH-A-RANDOM-SHARED-SECRET"
          leeway_seconds: 60

global:
  authentication:
    - jwt-user