Skip to content

This is the multi-page printable view of this section. .

Return to the regular view of this page.

Reference

Architecture, request deep dive, API key security, multi-tenancy, CORS, and model swap.

1 - Architecture & Request Flow

How Red Hat OpenShift AI Models as a Service works under the hood — what each component does and how a request travels from a user’s laptop to a model and back.

This page explains how Red Hat OpenShift AI Models as a Service works under the hood — what each component does and how a request travels from a user’s laptop to a model and back.

Tip

All file paths and oc apply commands in this guide are relative to the CAI-Field-Manual-MaaS repository root. Make sure you have cloned it and are working from its root directory (see Getting Started).

Important

This guide is not a replacement for the official Red Hat OpenShift AI Models as a Service documentation (3.5 | 3.4). It is a companion resource with opinionated Kustomize manifests and automation scripts to accelerate deployment.

Component Overview

Models as a Service is built from four layers, each with a distinct responsibility:

LayerComponentsRole
GatewayGateway API, IstioEntry point for all traffic. HTTPRoutes direct requests to the right model endpoint.
PolicyKuadrant, Authorino, LimitadorEnforce authentication, authorization, and rate limiting at the edge — before requests reach any model.
API & Tokenmaas-api, PostgreSQLAPI key lifecycle: mint, validate, and revoke sk-oai-* keys. Stores hashed keys and subscription bindings.
Model ServingKServe (LLMInferenceService), vLLM, ExternalModelRun inference. Internal models run as vLLM pods on-cluster; external models proxy to third-party APIs (Anthropic, OpenAI, etc.).

Request Flow: Step by Step

Here is what happens when a user makes an inference request, from their laptop to the model and back.

graph TB
    subgraph UserLayer["User"]
        U[User]
    end

    subgraph GatewayLayer["Gateway & Policy"]
        G[Gateway]
        MAP[MaaSAuthPolicy<br/>Authorino]
        MS[MaaSSubscription<br/>Limitador]
    end

    subgraph MaaSLayer["Token Management"]
        API[MaaS API]
    end

    subgraph ModelLayer["Model Serving"]
        INV[Inference Service]
        LLM[LLM]
    end

    U -->|"1. Inference + API key"| G
    G -->|"2. Validate identity"| MAP
    MAP -.->|"3. Validate key"| API
    MAP -->|"4. Check limits"| MS
    MS -.->|"5. Within limits"| INV
    INV -->|"6. Forward"| LLM
    LLM -->|"7. Completion"| U

    MAP -.->|"401/403"| U
    MS -.->|"429"| U

Diagram source: Upstream MaaS Architecture

1. Create an API Key

The user authenticates with their OpenShift token (or an external IdP token) and requests an API key:

curl -X POST https://maas.${CLUSTER_DOMAIN}/maas-api/v1/api-keys \
  -H "Authorization: Bearer <identity-token>" \
  -d '{"subscription": "my-subscription", "expiresIn": "24h"}'

Authorino validates the identity token. If valid, maas-api generates a random sk-oai-* key, hashes it with SHA-256, stores the hash and subscription binding in PostgreSQL, and returns the plaintext key once.

Note

The subscription field is optional. If you omit it, maas-api binds the highest-priority subscription your groups have access to. The field name is subscription (not subscriptionName).

2. Send an Inference Request

The user sends a chat completion request using the API key:

curl https://maas.${CLUSTER_DOMAIN}/v1/chat/completions \
  -H "Authorization: Bearer sk-oai-..." \
  -H "Content-Type: application/json" \
  -d '{"model": "my-model", "messages": [{"role": "user", "content": "Hello"}]}'

3. Gateway Receives the Request

The request hits the maas-default-gateway in the openshift-ingress namespace. The Gateway API controller (backed by Istio) matches the request against HTTPRoutes to determine which backend to forward to.

4. Authorino Validates the API Key

Before the request reaches any model, Authorino intercepts it (via MaaSAuthPolicy) and calls the maas-api /internal/v1/api-keys/validate endpoint:

  • Looks up the salted hash in PostgreSQL
  • Returns the user identity (username, groups, key ID) and the subscription name bound to that key
  • Rejects unknown, revoked, expired, or malformed keys with 401 Unauthorized

5. Subscription Access Check

Using the subscription name from the key record (not from client headers), Authorino checks:

  • Is the user/group allowed to use this subscription?
  • Is the requested model included in the subscription?

If either check fails, the request is rejected with 403 Forbidden.

6. Rate Limiting

Limitador checks the request against the rate limits defined in the MaaSSubscription CR:

  • Requests per minute/hour
  • Token budgets per time window

If the user has exceeded their limits, the request is rejected with 429 Too Many Requests.

7. Forward to Model

If all checks pass, the request is forwarded to the model backend:

  • Internal model (InferenceService): routed to a vLLM pod running on-cluster via KServe
  • External model (ExternalModel): proxied to a third-party API (e.g., Anthropic Claude, OpenAI GPT)

The model processes the request and returns a completion response.

8. Response Returns to User

The response flows back through the Gateway to the user. Limitador updates usage counters (tokens consumed, requests made) for the subscription.

Sequence Diagram

The full inference flow as a sequence diagram, showing every component interaction:

sequenceDiagram
    participant Client
    participant GatewayAPI
    participant Authorino
    participant MaaS as MaaS API
    participant Limitador
    participant LLMInferenceService

    Client->>GatewayAPI: Inference + API Key
    GatewayAPI->>Authorino: Validate credentials

    alt API key (sk-oai-*)
        Authorino->>MaaS: POST /internal/v1/api-keys/validate
        MaaS->>MaaS: Lookup hash in PostgreSQL
        MaaS-->>Authorino: { valid, userId, groups, subscription }
    end

    Authorino->>MaaS: POST /internal/v1/subscriptions/select (subscription check)
    MaaS-->>Authorino: Selected subscription

    Authorino->>GatewayAPI: Auth success (cached)
    GatewayAPI->>Limitador: Check TokenRateLimitPolicy
    Limitador-->>GatewayAPI: Within limits
    GatewayAPI->>LLMInferenceService: Forward request
    LLMInferenceService-->>Client: Response

Interactive Flow Visualizer

To see all of the above in action, explore the interactive animated visualizer — it walks through 5 complete flows (including auth failures and rate limiting) step by step with clickable components and a request/response inspector.

For pod-by-pod debugging with oc commands, see Request Deep Dive.

Note

5 Flows | 5 Providers | Two-stage IPP | 33 Steps | 30+ Components Corrected two-stage IPP (pre/post Kuadrant), WasmPlugin CRs, ExternalProvider/ExternalModel split, ipp-managed label, redhat-ai-gateway-infra namespace.

References

2 - Request Deep Dive: Pod-by-Pod Tracing

Traces an inference request through every pod in the Red Hat OpenShift AI 3.5 Models as a Service stack, with the oc commands to debug each hop.

This page traces an inference request through every pod in the Red Hat OpenShift AI 3.5 Models as a Service stack. Use it to understand where to look when debugging, what each component does to the request, and which oc commands to run.

Tip

For an animated walkthrough of these flows, see the RHOAI 3.5 Flow Visualizer .

Envoy Filter Chain (Inside the Gateway)

The maas-default-gateway Envoy proxy in openshift-ingress processes every request through this filter chain:

Envoy filter chain - 4 stages inside the Gateway
OrderFilterPod / MechanismWhat It Does
①ext_proc (IPP Pre)payload-pre-processingRuns two plugins: model-extractor (body-field-to-header) copies the model field from the body into the X-Gateway-Model-Name header, and model-provider-resolver resolves it. Runs BEFORE auth so Kuadrant can use the header for per-model policy matching.
②wasm (Kuadrant)WasmPlugin CR (in-process)Auth via Authorino (gRPC), rate limiting via Limitador (gRPC). Uses X-Gateway-Model-Name for route-level policy enforcement.
③ext_proc (IPP Post)payload-processingHeader guarding, usage enforcement, provider resolution, API format translation, credential injection. Runs AFTER auth completes.
④router(built-in)Routes the mutated request to the upstream - external provider API or on-cluster InferencePool/InferenceService.
# View the EnvoyFilter that configures the two-stage IPP
oc get envoyfilter payload-processing -n openshift-ingress -o yaml

# View the Kuadrant WasmPlugin
oc get wasmplugin -n openshift-ingress -o yaml

# View all filters on the gateway
oc get envoyfilters -n openshift-ingress

Namespace Map

Every component lives in a specific namespace. Here is the full layout for RHOAI 3.5:

RHOAI 3.5 namespace map
NamespaceComponentsPurpose
openshift-ingressmaas-default-gateway (Envoy), payload-pre-processing, payload-processing, istiod, kube-auth-proxy, router-defaultGateway, IPP ext_proc pods, Istio control plane
redhat-ai-gateway-inframaas-api, maas-api-key-cleanup (CronJob)API key management (moved from redhat-ods-applications in 3.5)
redhat-ods-applicationsmaas-controller, maas-ui, postgresMaaS controller, UI, PostgreSQL database
kuadrant-systemauthorino, limitador-limitadorAuth server, rate limit server
models-as-a-serviceMaaSAuthPolicy, MaaSSubscription CRsUser-facing access control and quota definitions
ai-tenantsAITenant CRsMulti-tenancy configuration
model namespace (e.g., llm)vLLM pods, MaaSModelRef, TokenRateLimitPolicy, LLMInferenceServiceModel serving workloads
external-models namespaceExternalProvider, ExternalModel CRsThird-party API proxy configuration
# Quick view of all MaaS-related pods across namespaces
oc get pods -n openshift-ingress -l app.kubernetes.io/part-of=maas 2>/dev/null; \
oc get pods -n redhat-ai-gateway-infra; \
oc get pods -n redhat-ods-applications | grep -E 'maas|postgres'; \
oc get pods -n kuadrant-system

Pod-by-Pod Request Trace

External Model Request (e.g., Anthropic)

External model request sequence
StepPodNamespaceWhat HappensDebug Command
1client-Sends POST /v1/chat/completions with Authorization: Bearer sk-oai-...curl -v https://maas.${CLUSTER_DOMAIN}/v1/chat/completions ...
2-4payload-pre-processingopenshift-ingressParses JSON body, extracts model field, sets X-Gateway-Model-Name header. Resolves model type.oc logs -n openshift-ingress deploy/payload-pre-processing -f
5-6maas-default-gateway (Wasm)openshift-ingressKuadrant WasmPlugin triggers auth-service actionoc logs -n openshift-ingress deploy/maas-default-gateway-istio -c istio-proxy -f
7authorinokuadrant-systemReceives gRPC call from Wasm shim. Calls MaaS API to validate the sk-oai-* key. On success, injects the identity headers (X-MaaS-Username, X-MaaS-Group, X-MaaS-Subscription) from the validation result via the MaaSAuthPolicy response stage.oc logs -n kuadrant-system deploy/authorino -f
8-9maas-apiredhat-ai-gateway-infraLooks up key hash in PostgreSQL. Returns the validation result {valid, userId, groups, subscription} to Authorino (a JSON body, not headers). The subscription comes from the key record bound at mint time.oc logs -n redhat-ai-gateway-infra deploy/maas-api -f
10limitador-limitadorkuadrant-systemReceives gRPC call from Wasm shim. Checks token quota for the subscription.oc logs -n kuadrant-system deploy/limitador-limitador -f
11-17payload-processingopenshift-ingressRuns post-processing plugins in order: maas-headers-guard, stream-usage-enforcer, model-provider-resolver (resolves ExternalModel CRD), api-translation (OpenAI to Anthropic format), apikey-injection (injects provider key from Secret).oc logs -n openshift-ingress deploy/payload-processing -f
18-19maas-default-gateway (router)openshift-ingressRoutes mutated request to https://api.anthropic.com/v1/messagesoc logs -n openshift-ingress deploy/maas-default-gateway-istio -c istio-proxy -f
20Anthropic API-Processes request, returns Anthropic Messages format response-
21-22payload-processingopenshift-ingressResponse plugins: api-translation converts Anthropic response back to OpenAI format (only when response translation is enabled - see note below)oc logs -n openshift-ingress deploy/payload-processing -f
23-25maas-default-gateway (Wasm)openshift-ingressKuadrant Wasm reads usage.total_tokens from response body. Reports consumed tokens to Limitador via gRPC.oc logs -n openshift-ingress deploy/maas-default-gateway-istio -c istio-proxy -f
26client-Receives OpenAI-format response regardless of which provider was used-
Note

Response api-translation is off by default. The payload-processing-plugins ConfigMap ships with an empty response profile (response: []) so streaming (SSE) is not held by a response processor. Providers that rewrite responses (for example Anthropic Messages to OpenAI) need it enabled manually on the ConfigMap. Steps 21-22 above only run once you opt in. See the upstream MaaS docs (External Model Setup - IPP response translation).

Internal Model Request (P/D Disaggregated)

Internal Model P/D disaggregated sequence

After step 16 (IPP Post returns to Gateway), the internal model flow diverges:

StepPodNamespaceWhat HappensDebug Command
17-19EPP (ext_proc)model namespaceEndpoint Picker selects optimal Prefill and Decode pods based on KV cache utilization and queue depthoc logs -n <model-ns> deploy/<epp-deploy> -f
20-21Sidecarmodel namespaceCoordinates the Prefill/Decode transactionoc logs -n <model-ns> <sidecar-pod> -f
22-23Prefill Pod (vLLM)model namespaceProcesses input prompt, generates KV cache, returns KVXfer metadataoc logs -n <model-ns> <prefill-pod> -c kserve-container -f
24-25NIXLmodel namespaceHigh-speed KV cache transfer from Prefill to Decode pod (GPU-direct RDMA or DCN)-
26-27Decode Pod (vLLM)model namespacePulls KV cache via NIXL, generates tokens auto-regressively, streams response back to Gatewayoc logs -n <model-ns> <decode-pod> -c kserve-container -f

Key Configuration Resources

CRD relationship hierarchy

These are the ConfigMaps, Secrets, and CRDs that control the request flow:

ResourceNamespacePurpose
ConfigMap/payload-processing-pluginsopenshift-ingressDefines which plugins run in IPP pre and post stages
Secret with label inference.llm-d.ai/ipp-managed=trueexternal-models namespaceProvider API keys for apikey-injection plugin (3.5 label; was bbr-managed in 3.4)
Config/default(cluster-scoped)Platform anchor CR that triggers MaaS controller reconciliation
AITenantai-tenantsMulti-tenancy configuration for the AI Gateway
MaaSModelRefmodel namespaceMaps user-facing model name to provider endpoint and target model ID
MaaSAuthPolicymodels-as-a-serviceConfigures API key authentication via K8s Secret
MaaSSubscriptionmodels-as-a-serviceDefines quota - associates user/team with allowed models and rate limits
ExternalProviderexternal-models namespaceProvider connection config (URL, auth type)
ExternalModelexternal-models namespaceMaps model name to provider and target model
AuthPolicyopenshift-ingressGenerated by maas-controller from MaaSAuthPolicy
TokenRateLimitPolicymodel namespaceGenerated by maas-controller from MaaSSubscription
# View IPP plugin configuration
oc get cm payload-processing-plugins -n openshift-ingress -o yaml

# View provider secrets (check label)
oc get secrets -l inference.llm-d.ai/ipp-managed=true -A

# View all MaaS CRDs
oc get maasmodelref -A
oc get maasauthpolicy -A
oc get maassubscription -A
oc get externalmodel -A
oc get externalprovider -A

# View platform config
oc get config default -o yaml
oc get aitenant -A

Common Debugging Scenarios

Debugging decision tree

500 Error on External Model

The request reaches the provider but credential injection failed:

# Check if the Secret has the correct label
oc get secrets -n <external-models-ns> -l inference.llm-d.ai/ipp-managed=true

# Check payload-processing logs for apikey-injection errors
oc logs -n openshift-ingress deploy/payload-processing | grep -i "apikey\|credential\|secret"

# Check ExternalModel CRD is correct
oc get externalmodel <model-name> -n <external-models-ns> -o yaml

401 Unauthorized

The API key is invalid, expired, or revoked:

# Check Authorino logs
oc logs -n kuadrant-system deploy/authorino | grep -i "denied\|reject\|invalid"

# Check MaaS API key validation
oc logs -n redhat-ai-gateway-infra deploy/maas-api | grep -i "validate\|invalid"

# Check MaaSAuthPolicy
oc get maasauthpolicy -A -o yaml

429 Too Many Requests

Token quota exceeded:

# Check Limitador logs
oc logs -n kuadrant-system deploy/limitador-limitador | grep -i "rate\|limit\|exceed"

# Check subscription limits
oc get maassubscription -A -o yaml | grep -A5 "rateLimits"

# Check TokenRateLimitPolicy
oc get tokenratelimitpolicy -A -o yaml

Model Not Found

The model name doesn’t match any MaaSModelRef:

# List all registered models
oc get maasmodelref -A

# Check payload-processing logs for resolver errors
oc logs -n openshift-ingress deploy/payload-processing | grep -i "resolver\|model.*not.*found"

# Check the pre-processing header extraction
oc logs -n openshift-ingress deploy/payload-pre-processing | grep -i "model\|header"

RHOAI 3.4 vs 3.5 Differences

RHOAI 3.4 vs 3.5 architecture comparison

If you are debugging a 3.4 cluster, these are the key differences:

What3.43.5
DSC componentkserve.modelsAsServiceaigateway.modelsAsAService
MaaS API namespaceredhat-ods-applicationsredhat-ai-gateway-infra
Secret labelinference.networking.k8s.io/bbr-managed=trueinference.llm-d.ai/ipp-managed=true
Kuadrant integrationEnvoyFilter-based WasmWasmPlugin CRs
External model CRDSingle ExternalModelExternalProvider + ExternalModel
IPP architectureSingle ext_proc stage (after auth)Two stages: pre (before auth) + post (after auth)
IPP plugins (post)model-provider-resolver, body-field-to-header, api-translation, apikey-injectionmaas-headers-guard, stream-usage-enforcer, model-provider-resolver, api-translation, apikey-injection

3 - API Key Security

A security reference for Red Hat OpenShift AI Models as a Service API keys, covering the full lifecycle of an sk-oai-* key from cryptographic generation through inference-time validation to expiry and revocation.

This page is a security reference for Red Hat OpenShift AI Models as a Service API keys. It covers the full lifecycle of an sk-oai-* key – from cryptographic generation through inference-time validation to expiry and revocation. For the high-level request flow, see Architecture & Request Flow. For pod-by-pod debugging, see Request Deep Dive.

Note

This page describes the security internals of the maas-api component. You do not need to understand these details to use Models as a Service, but they are useful for security reviews, incident response, and compliance documentation.

Key Anatomy

A Models as a Service API key has four components:

sk-oai-{key_id}_{secret}
╰─────╯ ╰──────╯ ╰──────╯
 prefix   96-bit   256-bit
 (fixed)  salt     secret
          (Base62) (Base62)
ComponentValuePurpose
sk-oai-Fixed stringIndustry convention prefix. Allows grep/scan tooling to detect leaked keys in logs and repos.
key_id96-bit Base62 (~16 chars)Per-key salt (FIPS 180-4 compliant). First input to the SHA-256 hash derivation.
_Underscore separatorUnambiguous boundary between key_id and secret.
secret256-bit Base62 (~43 chars)Cryptographic secret generated by crypto/rand. 256 bits of entropy makes brute-force infeasible (2^256 keyspace).

Hash Derivation

The maas-api never stores the plaintext key. Instead, it derives a hash at creation time:

SHA-256( key_id + "\x00" + secret )  →  key_hash (hex-encoded, stored)

The null byte (\x00) delimiter prevents ambiguous component boundaries. Without it, key_id "ab" + secret "cdef" would hash identically to key_id "abc" + secret "def".

Important

The plaintext key is returned exactly once in the HTTP response at creation time. There is no “retrieve my key” operation. If you lose the key, create a new one.

Key Creation

The key generation process uses OS-level cryptographic randomness:

  1. crypto/rand generates 12 random bytes (key_id) + 32 random bytes (secret)
  2. Both components are Base62-encoded
  3. The plaintext key is assembled as sk-oai-{key_id}_{secret}
  4. SHA-256(key_id + "\x00" + secret) is computed and stored in PostgreSQL
  5. The plaintext key is returned in the HTTP response body
  6. The server discards the plaintext from memory
# Create an API key (the plaintext key is shown once in the response)
DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
curl -sk -X POST \
  -H "Authorization: Bearer $(oc whoami -t)" \
  -H "Content-Type: application/json" \
  -d '{"name":"security-test","expiresIn":"1h","subscription":"<subscription-name>"}' \
  "https://maas.${DOMAIN}/maas-api/v1/api-keys" | jq .

The response contains the key field with the full plaintext. Subsequent GET requests return only metadata:

# List your keys (no plaintext in the response)
curl -sk -X POST \
  -H "Authorization: Bearer $(oc whoami -t)" \
  -H "Content-Type: application/json" \
  -d '{}' \
  "https://maas.${DOMAIN}/maas-api/v1/api-keys/search" | jq '.data[] | {id, name, status, creationDate, expirationDate}'
Warning

Store the key immediately upon creation. If you lose it, you must create a new one.

For the complete key creation procedure, see upstream: Create an API Key.

Persistence

The database stores identity and policy metadata, not the bearer secret:

StoredNot Stored
SHA-256 key_hash (hex-encoded)Plaintext API key
Database UUID (id)Secret component
Username, key name, descriptionDisplay prefix (sk-oai-XXXX...)
Immutable group snapshot (user_groups[])
Subscription, tenant
Status (active / revoked / expired)
Timestamps (created_at, expires_at, last_used_at)
Ephemeral flag
Note

Database access alone does not reveal usable keys. An attacker with full database read access must brute-force 256 bits of entropy to reconstruct a valid secret.

# View stored key metadata in PostgreSQL (no plaintext visible)
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas \
  -c "SELECT id, username, name, status, tenant, ephemeral, created_at, expires_at FROM api_keys LIMIT 5;"

# Confirm only the hash is stored, not the plaintext
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas \
  -c "SELECT id, left(key_hash, 16) || '...' as key_hash_prefix, length(key_hash) as hash_length FROM api_keys LIMIT 3;"

Validation Flow

Every inference request triggers API key validation on the hot path. The high-level flow is covered in Architecture: Authorino Validates the API Key. This section details the internal steps of ValidateAPIKey() inside maas-api.

sequenceDiagram
    participant App as Application
    participant GW as API Gateway
    participant Auth as Authorino
    participant API as MaaS API
    participant DB as PostgreSQL

    App->>GW: POST /v1/chat/completions<br/>Authorization: Bearer sk-oai-...
    GW->>Auth: gRPC auth check (Wasm shim)
    Auth->>API: POST /internal/v1/api-keys/validate

    rect rgb(240, 248, 255)
    Note over API: ValidateAPIKey()
    Note over API: 1. Format check (reject malformed)
    Note over API: 2. SHA-256(key_id + 0x00 + secret)
    API->>DB: SELECT WHERE key_hash=$1 AND tenant=$2
    DB-->>API: key record
    Note over API: 3. Expiry and status check
    Note over API: 4. Subscription check (fail closed)
    Note over API: 5. UUID validation
    end

    API-->>Auth: {valid, userId, groups, subscription}
    Note over API,DB: Async: update last_used_at (background, 2s timeout)
    Auth-->>GW: Auth success + identity headers
    GW->>App: Forward to model

ValidateAPIKey() Steps

  1. Format check – reject malformed keys before any database access. If the key does not match sk-oai-{key_id}_{secret}, return invalid immediately.
  2. SHA-256 hash – compute SHA-256(key_id + "\x00" + secret) to produce key_hash.
  3. Hash lookup – query PostgreSQL using the (key_hash, tenant) unique index. Single B-tree indexed lookup.
  4. Expiry and status check – reject if status != 'active' or expires_at < now().
  5. Subscription check (fail closed) – verify the key’s subscription exists and is valid. Missing subscription causes rejection.
  6. UUID validation (fail closed) – confirm the key’s UUID is well-formed. Invalid UUID causes rejection.
Rejection ReasonBehavior
Missing subscriptionReject (fail closed)
Invalid UUIDReject (fail closed)
Parse failureReject (fail closed)
Expired or revokedReject

Performance Characteristics

The validation design protects both the credential and the performance of the inference path:

TechniqueImplementationPurpose
Indexed lookupUNIQUE (key_hash, tenant) B-treeO(log n) validation on every inference request
Constant-time comparisoncrypto/subtle.ConstantTimeComparePrevents timing side-channel attacks that could leak hash information
Async usage trackingBackground goroutine + 2-second timeoutlast_used_at update never blocks the validation response path
Debounced updatessync.Map + CAS, TTL 60 secondsPrevents row-lock storms under high concurrency (CWE-362 safe)
# Watch validation in real-time during an inference request
oc logs -n redhat-ai-gateway-infra deploy/maas-api -f | grep "api-keys/validate\|subscriptions/select"

# Check Authorino calling the internal validate endpoint
oc logs -n kuadrant-system deploy/authorino -f | grep -i "api-key\|external"

Access Control

Authentication identifies the caller. Tenant and ownership rules determine which records that caller may operate on.

Tenant Isolation

Every database query includes WHERE tenant = $1. There is no code path that allows cross-tenant data access at the query level.

Owner-or-Admin

Users can see and revoke only their own keys. Admin privileges are detected via Kubernetes SubjectAccessReview – the maas-api checks whether the caller has admin permissions on the cluster, not through a separate admin flag in the database.

Unauthorized requests to key endpoints return 404 (not 403). This IDOR protection prevents attackers from enumerating valid key IDs by probing for different HTTP status codes.

Group Validation

Groups must match regex ^[a-zA-Z0-9:._-]+$. Groups are snapshotted at key creation time and never updated after that. This immutability prevents privilege escalation by modifying group membership after key creation.

# Verify IDOR protection: accessing a nonexistent key returns 404
DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
curl -sk -o /dev/null -w '%{http_code}' \
  -H "Authorization: Bearer $(oc whoami -t)" \
  "https://maas.${DOMAIN}/maas-api/v1/api-keys/nonexistent-uuid"

# Check access control in maas-api logs
oc logs -n redhat-ai-gateway-infra deploy/maas-api | grep -i "tenant\|denied\|403\|404"

Admin Key Management

Two questions come up regularly from administrators. Both answers follow directly from the ownership model above.

Can an Admin Create a Key Owned by Another User?

Not directly. POST /v1/api-keys has no owner or username field – the key always belongs to the identity of the Bearer token that created it, and it snapshots that identity’s group memberships (see Group Validation). This is by design: the groups baked into the key are what resolve the subscription, so the key must be minted from a token that actually carries the user’s groups.

Warning

A commonly suggested shortcut does not work:

oc --as=alice whoami -t   # returns YOUR token, not alice's

--as only adds impersonation headers to Kubernetes API requests. oc whoami -t prints the token from your kubeconfig without contacting the server, so the output is identical with and without --as (easy to verify: run both and compare). A key created with that token is owned by the admin – the maas-api resolves identity from a TokenReview of the presented token, and impersonation headers never reach it.

What works instead:

ApproachWhen to use it
Self-service (intended flow)The user creates their own key with their own token. This is the design center: keys are self-service, and admins govern through subscriptions and auth policies rather than by minting keys.
Token from the identity providerWith external OIDC (Phase 9), an admin who controls the IdP can obtain a token as the user (password grant or token exchange in Keycloak) and create the key with it. The key is then owned by the user with the user’s groups. This is exactly how the Phase 9 test script and the OIDC demos mint user-owned keys.
ServiceAccount tokenFor workloads rather than humans: oc create token <sa> -n <ns> mints a token whose identity is system:serviceaccount:<ns>:<sa>, and the key created with it is owned by the ServiceAccount. See the Service Account Access demo.

What admins can do to other users’ keys, per Owner-or-Admin: view, search, revoke individual keys, and bulk-revoke by username – just not create them.

Can the Number of Keys per User Be Capped?

There is no per-user key count limit in the current maas-api. Two things make this less of a problem than it sounds:

  • Extra keys do not multiply quota. Rate limits are counted per subscription, not per key. A user who mints five keys against the same subscription shares one token budget across all five – creating a second key does not reset or extend the limit. (The corporate scenario demo verifies exactly this: a second key is rate-limited immediately after the first key exhausts the subscription quota.)
  • Lifetime is capped centrally. The API_KEY_MAX_EXPIRATION_DAYS setting on the maas-api bounds how long any key can live, and ephemeral keys default to 1 hour, so unused key sprawl ages out.

For cleanup, admins can audit and bulk-revoke a user’s keys (dry run first):

DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')

# Preview what would be revoked for a user
curl -sk -X POST "https://maas.${DOMAIN}/maas-api/v1/api-keys/bulk-revoke" \
  -H "Authorization: Bearer $(oc whoami -t)" \
  -H "Content-Type: application/json" \
  -d '{"username": "alice", "dryRun": true}'

# Revoke them
curl -sk -X POST "https://maas.${DOMAIN}/maas-api/v1/api-keys/bulk-revoke" \
  -H "Authorization: Bearer $(oc whoami -t)" \
  -H "Content-Type: application/json" \
  -d '{"username": "alice"}'

Lifecycle

There are no permanent Models as a Service API keys. State transitions are one-way – there is no mechanism to reactivate a revoked or expired key.

graph TD
    A([ACTIVE]) -->|"Owner/admin revokes"| R([REVOKED])
    A -->|"expires_at reached"| E([EXPIRED])
    style A fill:#d5f5e3,stroke:#27ae60,color:#333
    style R fill:#f5b7b1,stroke:#e74c3c,color:#333
    style E fill:#fdebd0,stroke:#f39c12,color:#333

Standard Keys

  • Mandatory expiry controlled by API_KEY_MAX_EXPIRATION_DAYS environment variable on maas-api
  • Can be revoked by the key owner or a cluster admin at any time
  • Bulk revocation available for offboarding via POST /v1/api-keys/bulk-revoke
  • Key metadata is retained after expiry or revocation for audit purposes

Ephemeral Keys

  • Maximum 1 hour lifetime
  • Auto-cleaned by the maas-api-key-cleanup CronJob in redhat-ai-gateway-infra
  • Hard deleted 30 minutes after expiry via POST /internal/v1/api-keys/cleanup
  • Use case: temporary access for demos, CI/CD pipelines, testing

Database Constraints

The database enforces the lifecycle at the schema level:

CHECK (status IN ('active', 'revoked', 'expired'))

No reactivation is possible even via direct database manipulation.

Important

State transitions are one-way. There is no mechanism to reactivate a revoked or expired key. Create a new key instead.

# Check the cleanup CronJob
oc get cronjob -n redhat-ai-gateway-infra | grep cleanup

# View cleanup job history
oc get jobs -n redhat-ai-gateway-infra | grep cleanup

# Revoke a key
DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
curl -sk -X DELETE \
  -H "Authorization: Bearer $(oc whoami -t)" \
  "https://maas.${DOMAIN}/maas-api/v1/api-keys/<key-id>"

# Verify revocation in the database
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas \
  -c "SELECT id, status, expires_at FROM api_keys ORDER BY created_at DESC LIMIT 5;"

# List ephemeral keys
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas \
  -c "SELECT id, username, status, ephemeral, expires_at FROM api_keys WHERE ephemeral=true;"

Service Accounts

Service accounts are first-class Models as a Service API key identities. They use the same API, the same ValidateAPIKey() code path, and the same lifecycle rules as human users.

AspectDetail
IdentityKubernetes service account format: system:serviceaccount:<namespace>:<name>
BindingMaaSSubscription subjects.users (not groups) – direct user binding
ValidationSame API, same hash, same tenant scope
LifecycleSame expiry, revocation, and cleanup rules
# Check subscription owner bindings (groups and users)
oc get maassubscription -n models-as-a-service -o yaml | grep -A10 "owner:"

API Surface

Public management and internal validation are separate API surfaces with different trust boundaries.

Authenticated Endpoints (/v1/api-keys)

Auth via X-MaaS-Username and X-MaaS-Group headers injected by the ExtractUserInfo() middleware after Authorino validates the identity token. These headers are set by the gateway, not by the client.

MethodPathPurpose
GET/v1/api-keys/configGet API key configuration limits (max expiry, etc.)
POST/v1/api-keysCreate a new API key (returns plaintext once)
POST/v1/api-keys/searchSearch keys with filters, sort, pagination
POST/v1/api-keys/bulk-revokeRevoke all keys for a user (offboarding)
GET/v1/api-keys/:idRetrieve key metadata
DELETE/v1/api-keys/:idRevoke a specific key

Internal Endpoints (/internal/v1)

MethodPathCaller
POST/internal/v1/api-keys/validateAuthorino (on every inference request)
POST/internal/v1/api-keys/cleanupCronJob (ephemeral key cleanup)
POST/internal/v1/subscriptions/selectAuthorino (subscription resolution)
Warning

Internal APIs have no application-level authentication. Access is restricted by Kubernetes NetworkPolicy. This is a different trust boundary, not a defect – only pods in kuadrant-system and redhat-ai-gateway-infra can reach them.

# Verify NetworkPolicy restricting internal endpoints
oc get networkpolicy -n redhat-ai-gateway-infra -o yaml

# Test the health endpoint (public)
DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
curl -sk "https://maas.${DOMAIN}/maas-api/health"

# List your keys via the authenticated endpoint
curl -sk -X POST \
  -H "Authorization: Bearer $(oc whoami -t)" \
  -H "Content-Type: application/json" \
  -d '{}' \
  "https://maas.${DOMAIN}/maas-api/v1/api-keys/search" | jq .

Threat Model

No single control carries the security model. Each threat is addressed by a specific primary control:

ThreatAttack VectorPrimary Control
Credential guessingBrute-force the API key256-bit secret (2^256 keyspace)
Database breachRead DB to reconstruct keysHash-only storage (SHA-256, no plaintext)
Timing analysisMeasure response time to infer hash matchcrypto/subtle.ConstantTimeCompare
Cross-tenant accessUser A accesses User B’s keysTenant-scoped queries (WHERE tenant=$1)
ID enumerationProbe key IDs to discover valid ones404 for unauthorized (IDOR protection)
Forgotten credentialsOld keys remain active indefinitelyMandatory expiration (API_KEY_MAX_EXPIRATION_DAYS)
Update stormsHigh-concurrency last_used_at writesAsync debounce (sync.Map + CAS, 60s TTL)
OffboardingDeparted user’s keys remain activeBulk revocation (POST /v1/api-keys/bulk-revoke)
Tip

For incident response, use POST /v1/api-keys/bulk-revoke to immediately disable all keys for a departing user. This is faster than revoking keys one by one.

Database Schema

api_keys Table

ColumnTypeNotes
idTEXT (PK)UUID
usernameTEXT NOT NULLKey owner identity
nameTEXT NOT NULLUser-assigned key name
descriptionTEXTOptional description
key_hashTEXT NOT NULLSHA-256 hex digest
statusTEXT NOT NULLDEFAULT 'active'; CHECK IN ('active', 'revoked', 'expired')
user_groupsTEXT[] NOT NULLImmutable snapshot at creation
subscriptionTEXT NOT NULLBound subscription name
tenantTEXT NOT NULLTenant identifier
ephemeralBOOLEAN NOT NULLDEFAULT FALSE
created_atTIMESTAMPTZ NOT NULLCreation time
expires_atTIMESTAMPTZExpiry time
last_used_atTIMESTAMPTZLast validation time (async updated)

Indexes

IndexColumnsPurpose
Unique validation(key_hash, tenant)Fast lookup during ValidateAPIKey(); ensures no hash collisions within a tenant
Key listing(tenant, username, created_at)User-facing key list queries
Audit / cleanup(last_used_at) WHERE NOT NULLFind unused keys; cleanup CronJob
Group queries(user_groups) GINGroup-based access control queries
User key listing(username, created_at DESC)User-scoped key listing (without tenant filter)
Ephemeral cleanupPartial on status + expires_at WHERE ephemeral=trueCronJob: find expired ephemeral keys for deletion
# View the actual table schema
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas -c "\d api_keys"

# View indexes
oc exec -n redhat-ods-applications deploy/postgres -it -- \
  psql -U postgres -d maas -c "\di+ *api_keys*"

References

4 - Multi-Tenancy

A reference for Red Hat OpenShift AI Models as a Service multi-tenancy (RHOAI 3.5+): multiple MaaS tenants on one shared platform, isolation boundaries, and provisioning an additional tenant.

This page is a reference for Red Hat OpenShift AI Models as a Service multi-tenancy (RHOAI 3.5+). It answers the question that comes up in every architecture discussion: “Can we have a MaaS per team or per namespace in the same cluster?” The short answer: you get multiple MaaS tenants on one shared platform, not multiple independent MaaS instances. This page explains what that difference means, what is isolated, what is shared, and how to provision an additional tenant.

Important

MaaS multi-tenancy is a Technology Preview feature in RHOAI 3.5. Technology Preview features are not supported with Red Hat production service level agreements (SLAs) and might not be functionally complete. See the official RHOAI 3.5 multi-tenancy documentation for the supported scope.

Tenants, Not Instances

A tenant is a slice of one shared MaaS platform, bootstrapped by an AITenant custom resource. From the user’s point of view each tenant behaves like an independent MaaS environment: its own gateway hostname, its own identity configuration, its own API keys, subscriptions, and model catalog. From the platform’s point of view there is still one maas-controller, one PostgreSQL database, and one model serving infrastructure underneath.

What each tenant gets (dedicated):

ResourceDetail
GatewayA dedicated Gateway API Gateway with a unique hostname (e.g. finance-maas.apps.<cluster-domain>). The controller claims each Gateway for exactly one tenant - two AITenant resources cannot share a Gateway.
Tenant namespaceCreated as ai-tenant-<name> for additional tenants. Holds the tenant-scoped MaaS resources: MaaSSubscription, MaaSAuthPolicy, MaaSModelRef, and the tenant’s MaasTenantConfig.
API infrastructureA per-tenant maas-api instance (maas-api-<name> in redhat-ai-gateway-infra), plus gateway-scoped authentication and rate-limit policies for that tenant’s Gateway.
Identity realmEach tenant can point at its own OIDC issuer (spec.oidc on the AITenant), or fall back to OpenShift TokenReview. Tokens minted for one tenant are rejected by other tenants’ gateways.
RBAC RolesThe controller creates aitenant-<name>-tenant-admin (manage subscriptions, auth policies, tenant config in the tenant namespace) and aitenant-<name>-object-admin (read the AITenant object). You grant access by creating standard RoleBindings.

What stays shared across all tenants:

ResourceDetail
PostgreSQL databaseAll tenants store API keys in the same database instance. Keys are stored as salted SHA-256 hashes together with the username, group memberships, subscription, and tenant name, and every lookup is scoped by the (key_hash, tenant) index - a key created in tenant A returns 404 API key not found on tenant B’s gateway. See API Key Security for the full storage and validation internals.
maas-controllerOne controller reconciles all tenants.
Model serving infrastructureGPU nodes, model weights, and the serving stack (KServe / llm-d / vLLM) are cluster resources. Tenants govern access to models; they do not get dedicated copies of them.
Authorino and LimitadorPlatform-level authentication and rate limiting components are shared; the policies they enforce are per tenant.
Observability stackPrometheus, OTEL collectors, and dashboards are shared. Metrics, traces, and structured logs carry the tenant name, so usage can be filtered and attributed per tenant.

So “a MaaS per namespace” is not quite the model. The model is: one platform, and per team a tenant slice consisting of a gateway, a tenant namespace, and labeled model namespaces. Traffic separation comes from the dedicated gateways; governance separation comes from the tenant scoping in maas-api and the per-tenant policies.

Isolation Boundaries

The official docs list four cross-tenant protections, all enforced at the application layer:

  • API key rejection - a key created in one tenant returns HTTP 404 (API key not found) against another tenant’s gateway. Each tenant’s maas-api instance queries only its own tenant’s keys.
  • OIDC token rejection - tokens are validated against the tenant-specific identity provider configuration; tokens from another tenant’s IdP are rejected by the gateway AuthPolicy.
  • Subscription scoping - GET /v1/subscriptions returns only the requesting tenant’s data.
  • Model discovery scoping - GET /v1/models returns only models associated with the tenant through MaaSModelRef resources in the tenant namespace or with a matching tenantRef.
Note

Network-layer isolation is not part of MaaS tenancy. The boundaries above are gateway, identity, and RBAC boundaries. Pods in different tenant namespaces still share the cluster network. If your isolation requirements go further (e.g. tenants must not reach each other’s model pods directly, bypassing the gateway), add NetworkPolicies or, on OVN-Kubernetes, User Defined Networks (UDN) on top - that is standard OpenShift multi-tenancy hardening, independent of MaaS. This guide has not validated a UDN setup with MaaS.

The Default Tenant

Deploying MaaS (Phase 4) automatically creates the default tenant, which is exactly what this guide has been using all along:

oc get aitenant models-as-a-service -n ai-tenants
NAME                  READY   TENANT NAMESPACE      GATEWAY                AGE
models-as-a-service   True    models-as-a-service   maas-default-gateway   1h

The default tenant uses the models-as-a-service namespace and claims maas-default-gateway. On upgrade from 3.4, the controller migrates the old Tenant resource to a MaasTenantConfig, preserving API keys, subscriptions, and models.

Important

ExternalModel resources (Phase 8) are supported only in the default tenant. The controller disables the ExternalModel controller for non-default tenants (DISABLE_EXTERNAL_MODEL_CONTROLLER=true) to prevent HTTPRoute conflicts between tenant gateways. Access external models through the default tenant gateway.

Provisioning an Additional Tenant

Condensed from the official procedure. Prerequisites: the default tenant is Ready, cert-manager is installed, and RHCL is at Kuadrant v1.4.2 or later (the gateway-scoped AuthPolicy needs spec.defaults.rules).

Step 1: Pick a tenant name (DNS-1123 label, max 41 characters), detect the TLS certificate name (same derivation as Phase 2 - the official docs hardcode router-certs-default, which is wrong on clusters with a custom ingress certificate), and label the namespaces that must attach routes to the tenant Gateway:

TENANT_NAME="finance"
CLUSTER_DOMAIN=$(oc get ingresses.config.openshift.io cluster -o jsonpath='{.spec.domain}')
GATEWAY_HOSTNAME="${TENANT_NAME}-maas.${CLUSTER_DOMAIN}"

CERT_NAME=$(oc get ingresscontroller default -n openshift-ingress-operator \
  -o jsonpath='{.spec.defaultCertificate.name}' 2>/dev/null)
CERT_NAME="${CERT_NAME:-router-certs-default}"

# infrastructure namespace (per-tenant maas-api HTTPRoute)
oc label namespace redhat-ai-gateway-infra \
  "maas.opendatahub.io/gateway-access-${TENANT_NAME}=true" --overwrite

# every model namespace this tenant should serve from
oc label namespace <model_namespace> \
  "maas.opendatahub.io/gateway-access-${TENANT_NAME}=true" --overwrite

Step 2: Create the dedicated Gateway. The two annotations are required - opendatahub.io/managed: "false" keeps the ODH model controller from overriding MaaS policies, and the TLS bootstrap annotation enables Gateway-to-Authorino TLS (same pattern as Phase 2). The heredoc expands the variables from Step 1:

cat <<EOF | oc apply -f -
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: ${TENANT_NAME}
  namespace: openshift-ingress
  annotations:
    opendatahub.io/managed: "false"
    security.opendatahub.io/authorino-tls-bootstrap: "true"
spec:
  gatewayClassName: openshift-default
  listeners:
    - name: https
      hostname: "${GATEWAY_HOSTNAME}"
      port: 443
      protocol: HTTPS
      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels:
              maas.opendatahub.io/gateway-access-${TENANT_NAME}: "true"
      tls:
        mode: Terminate
        certificateRefs:
          - group: ""
            kind: Secret
            name: ${CERT_NAME}
EOF
Note

On non-cloud platforms (baremetal, SNO, OpenStack) the same LoadBalancer considerations as in Phase 2 apply: each additional Gateway needs its own external IP from MetalLB (extend the IPAddressPool), or a passthrough/reencrypt Route through the OpenShift router. Check whether the Gateway controller auto-provisioned a Route (oc get route -n openshift-ingress -l gateway.networking.k8s.io/gateway-name=<tenant-name>) and create one manually if not.

Step 3: Create the AITenant. It must live in the ai-tenants management namespace - the admission webhook rejects any other namespace:

cat <<EOF | oc apply -f -
apiVersion: maas.opendatahub.io/v1alpha1
kind: AITenant
metadata:
  name: ${TENANT_NAME}
  namespace: ai-tenants
spec:
  gateway:
    name: ${TENANT_NAME}
  # optional - per-tenant identity provider (BYOIDP), see Phase 9 for the Keycloak setup
  # oidc:
  #   issuerUrl: "https://<oidc_provider>/realms/<tenant_realm>"
  #   clientId: <client_id>
  #   ttl: 300
EOF

Step 4: Wait for the tenant to become Ready and verify the bootstrap:

oc get aitenant ${TENANT_NAME} -n ai-tenants -w

# tenant namespace, config, and per-tenant maas-api
oc get namespace ai-tenant-${TENANT_NAME}
oc get maastenantconfig default-tenant -n ai-tenant-${TENANT_NAME}
oc get deployment maas-api-${TENANT_NAME} -n redhat-ai-gateway-infra

# tenant endpoint answers with tenant-scoped models
curl -sk "https://${GATEWAY_HOSTNAME}/v1/models" \
  -H "Authorization: Bearer $(oc whoami -t)" | jq .

Step 5: Grant tenant admins access by binding the controller-created Roles (the spec.rbac field on AITenant is deprecated and ignored):

oc create rolebinding finance-tenant-admins \
  -n ai-tenant-${TENANT_NAME} \
  --role=aitenant-${TENANT_NAME}-tenant-admin \
  --group=finance-admins

From there, the tenant admin creates MaaSSubscription and MaaSAuthPolicy resources in the tenant namespace exactly as in Phase 5, and users mint API keys against the tenant’s own gateway hostname.

Deleting a Tenant

Delete the AITenant CR. The controller revokes the tenant’s API keys, removes the per-tenant maas-api, releases the Gateway claim, and deletes the controller-owned Roles and RoleBindings. User-created RoleBindings are preserved - review and remove stale ones before re-creating a tenant with the same name, or former admins regain access.

Quick Answers

QuestionAnswer
Can we run a MaaS per namespace in the same cluster?You run one MaaS platform with multiple isolated tenants. Each tenant maps to a dedicated gateway + tenant namespace + labeled model namespaces, not to an arbitrary namespace.
Multiple MaaS instances then?No - multiple tenants. One controller, one database, one serving infrastructure. The per-tenant pieces are the gateway, identity realm, namespace, maas-api instance, and policies.
Are the API keys separated?Logically yes, physically no. All keys live in the shared PostgreSQL database (as salted hashes with tenant metadata, see API Key Security), and every validation is tenant-scoped: a tenant A key gets 404 on tenant B’s gateway.
Can each tenant bring its own IdP?Yes - spec.oidc on the AITenant points that tenant at its own issuer. Without it, the tenant uses OpenShift TokenReview.
Are external models per tenant?No - ExternalModel works only in the default tenant in 3.5 (Technology Preview limitation).
Is there network isolation between tenants?Not from MaaS itself - isolation is at the gateway/identity/RBAC layer. Add NetworkPolicies or UDN separately if you need network-level separation.

References

5 - Browser Access (CORS)

Calling the Models as a Service gateway directly from a browser fails out of the box; this page shows the one EnvoyFilter that fixes both CORS preflights and response headers.

Calling the Models as a Service gateway directly from a browser – pointing a browser-based chat UI at https://<gateway-host> with a MaaS API key – fails out of the box: CORS preflights are rejected (404 or 401, depending on whether the gateway’s route matching or auth chain rejects OPTIONS first), and success responses carry no CORS headers. This page shows the one EnvoyFilter that fixes both.

Tip

Prerequisites: cluster-admin access on the MaaS cluster, at least one model deployed (local or external), and a MaaS API key. A key comes from POST /maas-api/v1/api-keys with your OpenShift token.

Important

Status: undocumented and unsupported in RHOAI/Kuadrant docs – but verified end-to-end on a live cluster (2026-09-22, RHOAI 3.5.1 + MaaS from this repo’s setup-maas.sh): all three CORS checks pass and the browser flow was confirmed working. Model-agnostic: the same gateway reconfiguration works for local models, external models, and the /maas-api/* control plane. No AuthPolicy changes – authentication is untouched.

What Has to Happen for CORS to Work

Three things, all on the gateway:

  1. Preflights must be answered before the auth filters run. Browsers never send Authorization on a CORS preflight (fetch spec: preflights are credentialless). Without the Lua filter, OPTIONS fails – typically 404 because no HTTPRoute matches the method, or 401 if the auth chain intercepts first:

    $ curl -i -X OPTIONS "https://<HOST>/v1/chat/completions" \
        -H "Origin: https://<your-app>" \
        -H "Access-Control-Request-Method: POST" \
        -H "Access-Control-Request-Headers: authorization, content-type"
    HTTP/2 404               <1>

    <1> May be 401 with x-ext-auth-reason: Authentication required on some Kuadrant/gateway configurations. Either way, CORS fails.

  2. Actual responses must carry CORS headers. A preflight alone is not enough – the browser also validates every real response (200, 401, 429, …). No access-control-allow-origin on a response means the browser blocks it from JavaScript.

  3. Never add a second set of CORS headers. OpenAI-compatible upstreams (LiteLLM-style) often run permissive CORSMiddleware and already emit access-control-allow-origin (plus access-control-allow-credentials: true). Adding another one merges into access-control-allow-origin: *,*, which browsers treat as invalid. Verified on-cluster 2026-09-22 – an unguarded headers():add() produced exactly that.

How to Reconfigure the Gateway

One EnvoyFilter. A Lua filter inserted FIRST in the gateway’s HTTP filter chain – before the Kuadrant WASM/ext-authz filters – does both jobs: it answers preflights itself (auth never sees them) and adds CORS headers to responses that the upstream did not already decorate. No AuthPolicy changes, no auth touched.

The applied, verified manifest is manifests/99-cors/envoyfilter-cors.yaml in the repo. The block below mirrors it – if the filter changes, update both together.

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: maas-cors-headers
  namespace: openshift-ingress
spec:
  workloadSelector:
    labels:
      gateway.networking.k8s.io/gateway-name: maas-default-gateway
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: GATEWAY
      listener:
        filterChain:
          filter:
            name: envoy.filters.network.http_connection_manager
    patch:
      operation: INSERT_FIRST
      value:
        name: envoy.filters.http.lua
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
          default_source_code:
            inline_string: |
              function envoy_on_request(request_handle)
                local method = request_handle:headers():get(":method")
                if method == "OPTIONS" and request_handle:headers():get("access-control-request-method") then
                  -- CORS preflight: answer here, before auth filters run
                  request_handle:respond({
                    [":status"] = "204",
                    ["access-control-allow-origin"] = "*",
                    ["access-control-allow-methods"] = "GET, POST, OPTIONS",
                    ["access-control-allow-headers"] = request_handle:headers():get("access-control-request-headers") or "authorization, content-type",
                    ["access-control-max-age"] = "86400"
                  })
                end
              end
              function envoy_on_response(response_handle)
                -- CORS headers on every response (200/401/429/...) — but only
                -- when the upstream did not already send them (OpenAI-compatible
                -- upstreams like LiteLLM run their own CORSMiddleware; adding
                -- again would merge into an invalid multi-value header)
                if not response_handle:headers():get("access-control-allow-origin") then
                  response_handle:headers():add("access-control-allow-origin", "*")
                  response_handle:headers():add("access-control-expose-headers", "x-request-id, retry-after")
                end
              end

Apply from the repository root:

oc apply -f manifests/99-cors/envoyfilter-cors.yaml

Three properties make this work:

  • operation: INSERT_FIRST – the Lua filter sits ahead of the Kuadrant ext-authz/WASM filters, so preflights are answered before auth can 401 them, and every response that comes back passes through the Lua on_response (including auth-generated 401s, which the upstream never sees).
  • The workloadSelector matches the gateway pods – verify the label with oc get pod -n openshift-ingress --show-labels. The generic istio: ingressgateway label would hit every gateway on the node.
  • The guard in on_response – only add CORS headers the upstream did not already send.

On anything shared, pin access-control-allow-origin to the real origin instead of * (both in the preflight respond() and in on_response).

Why Not the Alternatives

  • Native envoy.filters.http.cors filter (VIRTUAL_HOST/ROUTE typed_per_filter_config CorsPolicy): works – Istio ships it – but its position in the filter chain is not controllable. If the Kuadrant ext-authz filter is inserted before it, preflights 401 before the cors filter ever sees them. Lua INSERT_FIRST guarantees ordering. (header_mutation was also considered: it mutates headers but cannot answer preflights with local replies.)
  • AuthPolicy with an anonymous rule gated to OPTIONS (when: predicate: "request.method == 'OPTIONS'" – documented Kuadrant syntax, predicate per the Authorino 1.5.x features doc): only worth it if EnvoyFilters are blocked on your gateway. It is risky: the MaaS AuthPolicy on this setup is Gateway-targeting (maas-gateway-auth in openshift-ingress), and a route-level policy may REPLACE the gateway defaults for that route rather than OR-combine – the CRD says gateway defaults are enforced on “routes that lack a more specific policy attached to”. If it replaces, non-OPTIONS requests have no active authentication rules -> anonymous access -> the route silently opens. If you must, target the specific model HTTPRoute, then MANDATORY: verify an unauthenticated request still returns 401 and roll back (oc delete authpolicy allow-cors-preflight -n <HTTPROUTE_NS>) if it does not.
  • Authorino response headers (rules.response.unauthenticated.headers – documented CRD fields): makes the 401 carry CORS headers (error bodies readable in-browser) but NOT success responses – the CRD’s response.success.headers are “wrapped as HTTP headers to be injected in the request” (the upstream request, not the client response). Success-response CORS needs the EnvoyFilter or a permissive upstream.

Verify

# 1. Preflight: expect 204 WITH a single access-control-allow-origin
curl -sS -o /dev/null -D - -X OPTIONS "https://<HOST>/v1/chat/completions" \
  -H "Origin: <ALLOWED_ORIGIN>" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: authorization, content-type" | tr -d '\r'

# 2. Actual request WITH a key: expect 200 + CORS headers
curl -sS -o /dev/null -D - "https://<HOST>/v1/models" \
  -H "Origin: <ALLOWED_ORIGIN>" \
  -H "Authorization: Bearer <MAAS_KEY>" | tr -d '\r'

# 3. Actual request WITHOUT a key: expect 401 (auth untouched -- a 200 means
#    something else opened the route)
curl -sS -o /dev/null -w '%{http_code}\n' "https://<HOST>/v1/models" \
  -H "Origin: <ALLOWED_ORIGIN>"

Then the browser: point the chat UI at https://<HOST> with a MaaS key, click Test connection. Expect “Connected – N model(s)”.

Undo

One resource, one delete. The procedure on this page changed nothing else – auth, routes, and policies are untouched – and nothing re-creates the filter afterwards: setup-maas.sh never applies manifests/99-cors/, and cleanup-maas.sh never deletes it, so the whole lifecycle is manual.

  1. Check whether the filter is currently active. Resource existence is not proof – a silent NACK leaves the EnvoyFilter in place but ineffective. The preflight is answered before auth, so an unauthenticated OPTIONS is the cleanest probe: 204 means the filter is live, 404 means stock gateway behavior (OPTIONS does not match any HTTPRoute, so the gateway returns 404 before auth runs):

    oc get envoyfilter maas-cors-headers -n openshift-ingress
    
    # 204 = filter live, 404 = stock behavior (no CORS, no route match for OPTIONS)
    curl -sS -o /dev/null -w '%{http_code}\n' -X OPTIONS "https://<HOST>/v1/chat/completions" \
      -H "Origin: <ALLOWED_ORIGIN>" \
      -H "Access-Control-Request-Method: POST"
  2. Delete it:

    oc delete envoyfilter maas-cors-headers -n openshift-ingress
  3. Verify the rollback. Re-run the probe: expect 404 – without the Lua filter, OPTIONS does not match any HTTPRoute and the gateway returns 404 before auth runs. Re-run the three checks in the Verify section: expect no access-control-allow-origin on any response. The xDS config push is immediate; no pod restarts needed.

  • Access ends immediately. Browsers cache preflight decisions for up to 24h (access-control-max-age), but a cached preflight grants nothing after the delete: real responses stop carrying CORS headers, so the browser blocks them regardless. Cross-origin access ends as soon as the gateway stops emitting the headers.
  • Outlives teardown. A full cleanup-maas.sh run leaves maas-cors-headers (with * CORS) sitting in openshift-ingress on an otherwise torn-down gateway – delete it manually if you want the cluster clean. Platform upgrades do not re-create it: the MaaS controller re-applies only its own filters (such as authorino-tls-bootstrap), never this one.

Caveats

  • Silent NACK: if the listener update is rejected, Envoy keeps its last-known-good config – the EnvoyFilter resource still exists but CORS never appears. Check oc logs -n openshift-ingress deploy/maas-default-gateway-openshift-default -c istio-proxy for config rejections before concluding the filter applied.
  • Controller reconcile: the MaaS controller manages EnvoyFilters on this gateway (it creates the authorino-tls-bootstrap one itself) and may re-apply its own set on upgrade – re-check after platform upgrades.
  • If chat requests break: remove the filter first (oc delete envoyfilter maas-cors-headers -n openshift-ingress) – the MaaS disconnected setup shows the gateway falls back to deny-all when its WASM filter fails, so filter-chain interference is the prime suspect.

6 - Model Swap

Replace a model backend in Red Hat OpenShift AI Models as a Service without changing anything from the customer’s perspective — same API key, same model ID.

This page explains how to replace a model backend in Red Hat OpenShift AI Models as a Service without changing anything from the customer’s perspective - same API key, same model ID. The key is the MaaSModelRef abstraction layer that decouples the customer-facing API from the actual inference backend. Customers must use the body-based routing (BBR) endpoint (/v1/chat/completions) for seamless swaps.

Tip

All file paths and oc apply commands in this guide are relative to the CAI-Field-Manual-MaaS repository root. Make sure you have cloned it and are working from its root directory (see Getting Started).

Important

This guide is not a replacement for the official Red Hat OpenShift AI Models as a Service documentation (3.5 | 3.4). It is a companion resource with opinionated Kustomize manifests and automation scripts to accelerate deployment.

Overview

A model swap is the process of replacing the inference backend behind a model without affecting customers. Typical scenarios include:

  • Upgrading to a newer model version (e.g. Qwen 3.6 to Qwen 3.8)
  • Replacing a GPU model with a more efficient one
  • Moving from a simulator to a real model (or vice versa)
  • Switching hardware (e.g. different GPU type or node pool)

The swap works because MaaSModelRef acts as an indirection layer. Auth policies, subscriptions, and API keys all reference the MaaSModelRef by name - they have no knowledge of which LLMInferenceService sits behind it. Swapping the backend is a one-field patch.

Resource Hierarchy

Understanding how resources relate to each other is critical for a safe swap. Some resources are created by the admin, others are auto-created by maas-controller.

ResourceNamespaceCreated ByRole
LLMInferenceServicellm (model ns)AdminDefines the inference workload: container, model weights, resources, gateway routing. This is the actual serving pod.
MaaSModelRefllm (model ns)AdminRegisters the model with the MaaS control plane. Points to an LLMInferenceService (or ExternalModel) via spec.modelRef. This is the stable identity that customers interact with.
MaaSAuthPolicymodels-as-a-serviceAdminControls who can access the model. References MaaSModelRef by name + namespace.
MaaSSubscriptionmodels-as-a-serviceAdminDefines rate-limiting tiers. References MaaSModelRef by name + namespace. API keys are permanently bound to a subscription at creation time.
HTTPRoutellm (model ns)Controller (KServe)Routes traffic from the Gateway to the model pod. Created automatically when the LLMInferenceService is deployed.
TokenRateLimitPolicyllm (model ns)Controller (maas-controller)Enforces token rate limits from MaaSSubscription. Owned by the HTTPRoute - garbage collected when the HTTPRoute is deleted.
AuthPolicy (singleton)Gateway nsController (maas-controller)Shared gateway-level auth policy. One per gateway, not per model.

The Abstraction Layer

The diagram below shows how the resources connect. The MaaSModelRef is the pivot point - everything above it (auth, subscriptions, API keys) stays the same during a swap. Only the pointer below it (to the LLMInferenceService) changes.

Model Swap Architecture

MaaSModelRef Phase Transitions

The MaaSModelRef goes through these phases:

PhaseMeaning
PendingBackend is initializing or no governance pairing found yet.
ReadyBackend is healthy AND at least one MaaSSubscription + MaaSAuthPolicy pair is active. Inference is possible.
UnhealthyGovernance is attached but the backend has a runtime or health failure.
FailedNon-recoverable reconciliation error.
InvalidThe resource spec is missing or structurally invalid.

Governance means at least one MaaSSubscription AND one MaaSAuthPolicy both reference the same MaaSModelRef. Both are required for the model to reach Ready phase. These two CRDs are independent - updating one does NOT auto-update the other. For details on keeping them in sync, see Governance Pairing in Phase 5.

What Changes vs What Stays the Same

ComponentChanges?Why
LLMInferenceServiceYesNew backend deployed (qwen-38), old one deleted (qwen-36).
MaaSModelRef spec.modelRef.nameYesPointer swapped from qwen-36 to qwen-38.
MaaSModelRef nameNoqwen-coder is the stable identity that customers see. Keeping it the same is what makes the swap seamless.
MaaSAuthPolicyNoReferences MaaSModelRef qwen-coder by name (unchanged).
MaaSSubscriptionNoReferences MaaSModelRef qwen-coder by name (unchanged).
API keysNoBound to a subscription at creation time. Subscription is unchanged, so keys keep working.
Model ID in requestsNoBoth qwen-36 and qwen-38 serve the same spec.model.name (Qwen/Qwen3-Coder), so the canonical model ID (publishers/llm/models/Qwen/Qwen3-Coder) stays the same.
BBR endpoint (/v1/chat/completions)NoBody-based routing uses the canonical model ID in the request body (publishers/llm/models/Qwen/Qwen3-Coder), derived from the namespace and spec.model.name (both unchanged). Customers using this endpoint need no changes.
Per-model URL path (/llm/<name>/...)YesThe per-model URL path changes from /llm/qwen-36/... to /llm/qwen-38/... because it is derived from the LLMInferenceService name. Customers using per-model URLs must switch to the BBR endpoint.
Warning

The per-model URL path changes after a swap: /llm/qwen-36/v1/chat/completions becomes /llm/qwen-38/v1/chat/completions because it is derived from the LLMInferenceService name, not the MaaSModelRef name. Always use the BBR endpoint (/v1/chat/completions) with the full publisher model ID in the request body (e.g. publishers/llm/models/Qwen/Qwen3-Coder) for swap-safe client integration.

Prerequisites

  • Phases 1-5 completed (Red Hat OpenShift AI installed, Models as a Service platform running, llm namespace created)
  • Admin access to the model namespace and models-as-a-service namespace

Swap Procedure

This procedure walks through the full swap lifecycle using the provided Qwen 3.6 -> 3.8 simulator templates. Both templates use the CPU simulator image (llm-d-inference-sim), so no GPU is required.

The scenario: you have a model called qwen-36 registered with MaaS through a MaaSModelRef called qwen-coder. You want to replace it with qwen-38 without affecting customers.

Tip

If you already have a model deployed from Phase 5, you can skip the original model deployment and adapt the steps to your existing model names.

Step 1: Deploy the Original Model

Deploy the original model (qwen-36) with its full MaaS stack (MaaSModelRef, AuthPolicy, Subscriptions):

oc apply -k manifests/99-model-swap/qwen-36/

Wait for the model to become Ready:

oc wait llminferenceservice qwen-36 -n llm --for=condition=Ready --timeout=300s
oc get maasmodelref -n llm -o wide

Expected output:

NAME          PHASE   ENDPOINT                                                  HTTPROUTE                GATEWAY              AGE
qwen-coder    Ready   https://maas.<cluster-domain>/                            qwen-36-kserve-route     maas-default-gateway  ...

Step 2: Deploy the Replacement Model

Deploy the replacement (qwen-38) alongside the existing one:

oc apply -k manifests/99-model-swap/qwen-38/
Important

The new LLMInferenceService must use the same spec.model.name as the existing one. Both qwen-36 and qwen-38 use Qwen/Qwen3-Coder. This is the model ID that customers send in their API requests (/v1/chat/completions). If the names differ, customers would need to update their client code.

Step 3: Verify the Replacement is Ready

Wait for both LLMInferenceServices to be running:

oc get llminferenceservice -n llm

Expected output - both old and new show a Ready condition:

NAME       READY   ...
qwen-36    True    ...
qwen-38    True    ...

For GPU models, this can take 5-15 minutes while the image is pulled and model weights are loaded.

Step 4: Swap the MaaSModelRef Pointer

This is the swap itself. Patch the MaaSModelRef to point to the new LLMInferenceService:

oc patch maasmodelref qwen-coder -n llm --type=merge \
  -p '{"spec":{"modelRef":{"name":"qwen-38"}}}'

This one-field change is what makes the swap seamless. The MaaSModelRef name (qwen-coder) stays the same, so all auth policies, subscriptions, and API keys continue to work.

Verify the MaaSModelRef now points to qwen-38:

oc get maasmodelref qwen-coder -n llm -o jsonpath='{.spec.modelRef.name}'
# Expected: qwen-38

Step 5: Delete the Old LLMInferenceService

While both LLMInferenceServices exist, the gateway routes 100% of BBR traffic to qwen-36 (the first-created backend) and 0% to qwen-38. You must delete qwen-36 so the gateway starts routing to qwen-38.

Note

This means the swap is not zero-downtime. There is a brief window (typically a few seconds) between deleting the old model and the gateway routing to the new one where requests may fail.

oc delete llminferenceservice qwen-36 -n llm

This deletes the old inference pods, its HTTPRoute, and frees any GPU resources it was using.

Step 6: Clean Up Stale TokenRateLimitPolicy

After swapping the MaaSModelRef and deleting the old LLMInferenceService, the TokenRateLimitPolicy (TRLP) may retain an owner reference to the old HTTPRoute. This causes the MaaSSubscription to go Failed because the TRLP references a non-existent route.

Delete the stale TRLP so the controller can recreate it with the correct owner reference:

oc delete tokenratelimitpolicy maas-trlp-qwen-coder -n llm

The maas-controller will automatically recreate the TRLP, now correctly owned by the new HTTPRoute.

Step 7: Verify

Confirm that everything is healthy:

# MaaSModelRef should be Ready
oc get maasmodelref -n llm -o wide

# Only the new LLMInferenceService should exist
oc get llminferenceservice -n llm

# Subscriptions should be active (not Failed)
oc get maassubscription -n models-as-a-service

# TRLP should exist and reference the new HTTPRoute
oc get tokenratelimitpolicy -n llm

Test inference to confirm the swap worked. If you already have an API key from before the swap, use it - the whole point is that existing keys keep working. If you need a new one:

CLUSTER_DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
MAAS_URL="maas.${CLUSTER_DOMAIN}"

# Get admin token
TOKEN=$(oc create token admin-user -n models-as-a-service --duration=1h)

# Create API key (bound to the qwen-coder-free subscription)
API_KEY=$(curl -sk -X POST "https://${MAAS_URL}/v1/api-keys" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"name":"swap-test","description":"Post-swap verification","subscription":"qwen-coder-free"}' | \
  python3 -c "import sys,json; print(json.load(sys.stdin)['key'])")
echo "API_KEY=${API_KEY}"

Send an inference request using the BBR endpoint:

curl -sk "https://${MAAS_URL}/v1/chat/completions" \
  -H "Authorization: Bearer ${API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "publishers/llm/models/Qwen/Qwen3-Coder",
    "messages": [{"role": "user", "content": "Hello!"}]
  }' | jq .

A successful response confirms the swap is complete - the request was routed to qwen-38 using the same model ID and API key that worked with qwen-36.

Note

The model ID in the request body must be the full publisher path as returned by /v1/models (e.g. publishers/llm/models/Qwen/Qwen3-Coder). Using the short name (Qwen/Qwen3-Coder) returns a 404.

Operational Notes

Warning

BBR Routing Conflict

When two LLMInferenceServices in the same namespace share the same spec.model.name, their HTTPRoutes create identical BBR match rules. The gateway accepts both routes but routes 100% of traffic to the first-created backend - the new model receives zero requests. This was validated on OpenShift 4.21: 10/10 requests hit the old pod, 0/10 hit the new one. Deleting the old LLMInferenceService removes its HTTPRoute and lets the gateway discover the new one. There is no way to “test the new model first” while the old one exists.

Warning

TokenRateLimitPolicy Stale Owner Reference

The TokenRateLimitPolicy is auto-created by maas-controller and owned by the HTTPRoute. When the MaaSModelRef pointer changes, the TRLP still references the old HTTPRoute. Deleting the TRLP (Step 6) lets the controller recreate it with the correct owner. If you skip this, the MaaSSubscription may go Failed with an error like: Object <namespace>/maas-trlp-<name> is already owned by another HTTPRoute.

Note

endpointOverride

If you created the MaaSModelRef manually (not through the Kustomize manifests in Phase 5), the controller may not be able to auto-discover the endpoint URL. In that case, set spec.endpointOverride on the MaaSModelRef:

oc patch maasmodelref <name> -n llm --type=merge \
  -p '{"spec":{"endpointOverride":"https://maas.<cluster-domain>/"}}'

You can check if this is needed by looking at the MaaSModelRef status. If it is stuck in Unhealthy with an empty endpoint, endpointOverride is the fix.

Note

Model ID Format

The model ID used in inference requests (/v1/chat/completions) is the full publisher path, not the short model name. For example:

  • Short name: Qwen/Qwen3-Coder
  • Full publisher path: publishers/llm/models/Qwen/Qwen3-Coder

Always use the model ID as returned by the /v1/models endpoint to avoid 404 errors.

Template Manifests

The manifests/99-model-swap/ directory contains two concrete simulator-based templates that walk through the full swap lifecycle (Qwen 3.6 -> 3.8):

99-model-swap/
  qwen-36/                             # Original model (deploy first)
    kustomization.yaml                 # Aggregates llm/ and maas/
    llm/
      kustomization.yaml               # Sets namespace: llm
      model.yaml                       # LLMInferenceService: qwen-36
    maas/
      kustomization.yaml               # MaaS governance resources
      maas-model.yaml                  # MaaSModelRef: qwen-coder -> qwen-36
      maas-auth-policy.yaml            # MaaSAuthPolicy: qwen-coder-access
      maas-subscription-free.yaml      # Free tier (100 tokens/min)
      maas-subscription-premium.yaml   # Premium tier (100000 tokens/min)
  qwen-38/                             # Replacement model (deploy second)
    kustomization.yaml                 # Aggregates llm/ only
    llm/
      kustomization.yaml               # Sets namespace: llm
      model.yaml                       # LLMInferenceService: qwen-38

Both templates use the CPU simulator image (llm-d-inference-sim), so no GPU is required. Both share spec.model.name: Qwen/Qwen3-Coder - this is the invariant that makes the swap seamless.

The qwen-36/ directory includes the full MaaS stack (MaaSModelRef + AuthPolicy + Subscriptions) because it is the original deployment. The qwen-38/ directory only includes the LLMInferenceService because the MaaS governance resources persist unchanged across the swap - only the MaaSModelRef pointer changes.

For a real swap with GPU models, replace the container image, model URI, and resource requests in both model.yaml files to match your actual models.

References