Skip to content

auth-apikey

The internal:auth-apikey interceptor validates an API key passed in a request header against an expected value stored in an environment variable. It uses timing-safe comparison to prevent timing attacks.

actions:
- target: "$.paths['/api'].get"
update:
x-plenum-interceptor:
- module: "internal:auth-apikey"
hook: on_request_headers
function: checkApiKey
options:
header: "x-api-key"
envVar: "API_KEY"
permissions:
env: ["API_KEY"]
HookFunctionCan short-circuit
on_request_headerscheckApiKeyYes

Using on_request_headers ensures the request body is never read if authentication fails, saving resources.

FieldTypeDefaultDescription
headerstring— (required)Name of the request header containing the API key
envVarstring— (required)Name of the environment variable holding the expected key

The interceptor reads process.env to retrieve the expected key. Grant env permission for the environment variable:

permissions:
env: ["API_KEY"]

Without this permission the interceptor returns 500. See Interceptor Permissions for details.

StatusCondition
500options.header or options.envVar is missing
500The environment variable is not set
401The header is missing, or the key does not match

The 401 response body is {"error": "Unauthorized"}.

  • Comparison uses crypto.timingSafeEqual to prevent timing side-channel attacks.
  • If the header value and expected key have different lengths, the comparison always returns false.
  • Returns { action: "continue" } on success.

Protect all endpoints under /admin:

actions:
- target: "$.paths[/admin/*]"
update:
x-plenum-interceptor:
- module: "internal:auth-apikey"
hook: on_request_headers
function: checkApiKey
options:
header: "x-api-key"
envVar: "ADMIN_API_KEY"
permissions:
env: ["ADMIN_API_KEY"]