Skip to content

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