API Key Security
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.
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:
| Component | Value | Purpose |
|---|---|---|
sk-oai- | Fixed string | Industry convention prefix. Allows grep/scan tooling to detect leaked keys in logs and repos. |
key_id | 96-bit Base62 (~16 chars) | Per-key salt (FIPS 180-4 compliant). First input to the SHA-256 hash derivation. |
_ | Underscore separator | Unambiguous boundary between key_id and secret. |
secret | 256-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:
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".
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:
crypto/randgenerates 12 random bytes (key_id) + 32 random bytes (secret)- Both components are Base62-encoded
- The plaintext key is assembled as
sk-oai-{key_id}_{secret} SHA-256(key_id + "\x00" + secret)is computed and stored in PostgreSQL- The plaintext key is returned in the HTTP response body
- The server discards the plaintext from memory
The response contains the key field with the full plaintext. Subsequent GET requests return only metadata:
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:
| Stored | Not Stored |
|---|---|
SHA-256 key_hash (hex-encoded) | Plaintext API key |
Database UUID (id) | Secret component |
| Username, key name, description | Display 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 |
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.
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
- Format check – reject malformed keys before any database access. If the key does not match
sk-oai-{key_id}_{secret}, return invalid immediately. - SHA-256 hash – compute
SHA-256(key_id + "\x00" + secret)to producekey_hash. - Hash lookup – query PostgreSQL using the
(key_hash, tenant)unique index. Single B-tree indexed lookup. - Expiry and status check – reject if
status != 'active'orexpires_at < now(). - Subscription check (fail closed) – verify the key’s subscription exists and is valid. Missing subscription causes rejection.
- UUID validation (fail closed) – confirm the key’s UUID is well-formed. Invalid UUID causes rejection.
| Rejection Reason | Behavior |
|---|---|
| Missing subscription | Reject (fail closed) |
| Invalid UUID | Reject (fail closed) |
| Parse failure | Reject (fail closed) |
| Expired or revoked | Reject |
Performance Characteristics
The validation design protects both the credential and the performance of the inference path:
| Technique | Implementation | Purpose |
|---|---|---|
| Indexed lookup | UNIQUE (key_hash, tenant) B-tree | O(log n) validation on every inference request |
| Constant-time comparison | crypto/subtle.ConstantTimeCompare | Prevents timing side-channel attacks that could leak hash information |
| Async usage tracking | Background goroutine + 2-second timeout | last_used_at update never blocks the validation response path |
| Debounced updates | sync.Map + CAS, TTL 60 seconds | Prevents row-lock storms under high concurrency (CWE-362 safe) |
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.
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.
A commonly suggested shortcut does not work:
--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:
| Approach | When 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 provider | With 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 token | For 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_DAYSsetting 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):
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_DAYSenvironment 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-cleanupCronJob inredhat-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:
No reactivation is possible even via direct database manipulation.
State transitions are one-way. There is no mechanism to reactivate a revoked or expired key. Create a new key instead.
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.
| Aspect | Detail |
|---|---|
| Identity | Kubernetes service account format: system:serviceaccount:<namespace>:<name> |
| Binding | MaaSSubscription subjects.users (not groups) – direct user binding |
| Validation | Same API, same hash, same tenant scope |
| Lifecycle | Same expiry, revocation, and cleanup rules |
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.
| Method | Path | Purpose |
|---|---|---|
GET | /v1/api-keys/config | Get API key configuration limits (max expiry, etc.) |
POST | /v1/api-keys | Create a new API key (returns plaintext once) |
POST | /v1/api-keys/search | Search keys with filters, sort, pagination |
POST | /v1/api-keys/bulk-revoke | Revoke all keys for a user (offboarding) |
GET | /v1/api-keys/:id | Retrieve key metadata |
DELETE | /v1/api-keys/:id | Revoke a specific key |
Internal Endpoints (/internal/v1)
| Method | Path | Caller |
|---|---|---|
POST | /internal/v1/api-keys/validate | Authorino (on every inference request) |
POST | /internal/v1/api-keys/cleanup | CronJob (ephemeral key cleanup) |
POST | /internal/v1/subscriptions/select | Authorino (subscription resolution) |
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.
Threat Model
No single control carries the security model. Each threat is addressed by a specific primary control:
| Threat | Attack Vector | Primary Control |
|---|---|---|
| Credential guessing | Brute-force the API key | 256-bit secret (2^256 keyspace) |
| Database breach | Read DB to reconstruct keys | Hash-only storage (SHA-256, no plaintext) |
| Timing analysis | Measure response time to infer hash match | crypto/subtle.ConstantTimeCompare |
| Cross-tenant access | User A accesses User B’s keys | Tenant-scoped queries (WHERE tenant=$1) |
| ID enumeration | Probe key IDs to discover valid ones | 404 for unauthorized (IDOR protection) |
| Forgotten credentials | Old keys remain active indefinitely | Mandatory expiration (API_KEY_MAX_EXPIRATION_DAYS) |
| Update storms | High-concurrency last_used_at writes | Async debounce (sync.Map + CAS, 60s TTL) |
| Offboarding | Departed user’s keys remain active | Bulk revocation (POST /v1/api-keys/bulk-revoke) |
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
| Column | Type | Notes |
|---|---|---|
id | TEXT (PK) | UUID |
username | TEXT NOT NULL | Key owner identity |
name | TEXT NOT NULL | User-assigned key name |
description | TEXT | Optional description |
key_hash | TEXT NOT NULL | SHA-256 hex digest |
status | TEXT NOT NULL | DEFAULT 'active'; CHECK IN ('active', 'revoked', 'expired') |
user_groups | TEXT[] NOT NULL | Immutable snapshot at creation |
subscription | TEXT NOT NULL | Bound subscription name |
tenant | TEXT NOT NULL | Tenant identifier |
ephemeral | BOOLEAN NOT NULL | DEFAULT FALSE |
created_at | TIMESTAMPTZ NOT NULL | Creation time |
expires_at | TIMESTAMPTZ | Expiry time |
last_used_at | TIMESTAMPTZ | Last validation time (async updated) |
Indexes
| Index | Columns | Purpose |
|---|---|---|
| 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 NULL | Find unused keys; cleanup CronJob |
| Group queries | (user_groups) GIN | Group-based access control queries |
| User key listing | (username, created_at DESC) | User-scoped key listing (without tenant filter) |
| Ephemeral cleanup | Partial on status + expires_at WHERE ephemeral=true | CronJob: find expired ephemeral keys for deletion |
References
- Architecture & Request Flow – high-level Models as a Service component overview and request flow
- Request Deep Dive – pod-by-pod debugging with
occommands - Upstream: API Key Management
- Upstream: MaaS Architecture