# 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.

---

LLMS index: [llms.txt](/CAI-Field-Manual-Library/llms.txt)

---

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](/CAI-Field-Manual-Library/maas/reference/architecture/). For pod-by-pod debugging, see [Request Deep Dive](/CAI-Field-Manual-Library/maas/reference/request-deepdive/).

> [!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:

```text
sk-oai-{key_id}_{secret}
╰─────╯ ╰──────╯ ╰──────╯
 prefix   96-bit   256-bit
 (fixed)  salt     secret
          (Base62) (Base62)
```

| 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:

```text
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

```sh
# 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:

```sh
# 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](https://opendatahub-io.github.io/models-as-a-service/latest/user-guide/api-key-management/#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 | |

> [!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.

```sh
# 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](/CAI-Field-Manual-Library/maas/reference/architecture/#4-authorino-validates-the-api-key). This section details the internal steps of `ValidateAPIKey()` inside maas-api.

```mermaid
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 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) |

```sh
# 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.

```sh
# 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](#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:
>
> ```sh
> 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:

| 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](/CAI-Field-Manual-Library/maas/external-oidc/)), 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](https://github.com/rh-aiservices-bu/CAI-Field-Manual-MaaS/tree/main/demo/service-account-access). |

What admins **can** do to other users' keys, per [Owner-or-Admin](#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):

```sh
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.

```mermaid
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:

```text
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.

```sh
# 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.

| 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 |

```sh
# 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.

| 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) |

> [!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.

```sh
# 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:

| 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`) |

> [!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

| 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 |

```sh
# 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

- [Architecture & Request Flow](/CAI-Field-Manual-Library/maas/reference/architecture/) -- high-level Models as a Service component overview and request flow
- [Request Deep Dive](/CAI-Field-Manual-Library/maas/reference/request-deepdive/) -- pod-by-pod debugging with `oc` commands
- [Upstream: API Key Management](https://opendatahub-io.github.io/models-as-a-service/latest/user-guide/api-key-management/#create-an-api-key)
- [Upstream: MaaS Architecture](https://opendatahub-io.github.io/models-as-a-service/latest/concepts/architecture/)
