Skip to content

Latest commit

 

History

History
417 lines (301 loc) · 20.5 KB

authentication.md

File metadata and controls

417 lines (301 loc) · 20.5 KB

Authentication

This document describes authentication mechanisms for the HyperFleet API.

Table of Contents

Overview

HyperFleet API supports the following authentication modes:

  1. Development Mode (No Auth): For local development and testing without authentication
  2. Development with JWT (Google Cloud): Local development with real JWT validation using Google identity tokens
  3. Production Mode (JWT Auth): JWT-based authentication with configurable issuer

Development Mode (No Auth)

For local development and testing, authentication can be disabled.

Usage

# Start service without authentication or TLS
make run-no-auth

# Access API without tokens
curl http://localhost:8000/api/hyperfleet/v1/clusters | jq

Configuration

export HYPERFLEET_SERVER_JWT_ENABLED=false
./bin/hyperfleet-api serve

Caller identity in development mode

When JWT is disabled, caller identity resolution is inactive. Audit fields (created_by, updated_by, deleted_by) fall back to system@hyperfleet.local.

When JWT is enabled, mutating requests (POST, PATCH, PUT, DELETE) that cannot resolve a caller identity are rejected with 401 Unauthorized. Read requests (GET, LIST) are allowed without identity.

The identity_header field is per-issuer and only takes effect when JWT is enabled. When configured, a trusted gateway can override the JWT claim by setting this header:

# Mutating request with identity header (JWT must still be valid)
curl -X POST http://localhost:8000/api/hyperfleet/v1/clusters \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-HyperFleet-Identity: dev-user@local" \
  -H "Content-Type: application/json" \
  -d '{"kind":"Cluster","name":"my-cluster","spec":{}}'

# Read requests work without identity
curl http://localhost:8000/api/hyperfleet/v1/clusters | jq

See Caller identity for audit below for full details.

Important: Never disable authentication in production environments.

Development with JWT (Google Cloud)

For local development with real JWT validation, you can use Google Cloud identity tokens. This gives you proper authentication and caller identity without deploying a dedicated identity provider.

Prerequisites

Start the server

Configure via YAML (per-issuer JWT config, no CLI flags for configs):

server:
  jwt:
    enabled: true
    configs:
      - issuer_url: "https://accounts.google.com"
        jwk_cert_url: "https://www.googleapis.com/oauth2/v3/certs"
        header: Authorization
        audience: "32555940559.apps.googleusercontent.com"
        identity_claim: "email"
        identity_claim_pattern: ""
        identity_header: "X-HyperFleet-Identity"
./bin/hyperfleet-api serve --config config.yaml \
  --db-host localhost --db-port 5432 --db-name hyperfleet --db-username hyperfleet

The audience 32555940559.apps.googleusercontent.com is the default gcloud CLI OAuth client ID. It matches the aud claim in tokens generated by gcloud auth print-identity-token.

Generate a token and make requests

# Generate an identity token (valid for ~1 hour)
TOKEN=$(gcloud auth print-identity-token)

# List clusters
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:8000/api/hyperfleet/v1/clusters | jq

# Create a cluster (created_by will be your Google email)
curl -X POST http://localhost:8000/api/hyperfleet/v1/clusters \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"kind":"Cluster","name":"my-cluster","spec":{}}'

# Override identity via header (header takes precedence over JWT)
curl -X POST http://localhost:8000/api/hyperfleet/v1/clusters \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "X-HyperFleet-Identity: gateway-user@corp.com" \
  -d '{"kind":"Cluster","name":"my-cluster-2","spec":{}}'

How it works

Google identity tokens are standard OIDC JWTs signed by Google's keys. The server validates them like any other JWT:

  1. Fetches Google's public keys from the configured jwk_cert_url in the issuer config
  2. Verifies the RS256 signature
  3. Checks iss matches https://accounts.google.com
  4. Checks aud matches the configured audience
  5. Extracts the email claim for caller identity

You can inspect your token with:

gcloud auth print-identity-token | cut -d. -f2 | base64 -d 2>/dev/null | jq

Production Mode (JWT Auth)

Production deployments use JWT-based authentication with a configurable issuer.

Usage

# Terminal 1: start service with authentication (auto-generates dev JWT at /tmp/hf-dev-token.txt)
make run

# Terminal 2: access API with the generated token
curl -H "Authorization: Bearer $(cat /tmp/hf-dev-token.txt)" \
  http://localhost:8000/api/hyperfleet/v1/clusters

JWT Authentication

HyperFleet API validates JWT tokens using RS256 signature verification.

Token validation checks:

  1. Signature - Token signed by trusted issuer
  2. Issuer - Matches one of the configured issuer_url values in server.jwt.configs
  3. Audience - Matches the audience configured for that issuer
  4. Expiration - Token not expired
  5. Claims - Required claims present

Token format:

Authorization: Bearer <jwt-token>

Example request:

curl -H "Authorization: Bearer ${TOKEN}" \
  http://localhost:8000/api/hyperfleet/v1/clusters

Issuer configuration reference

Each entry in server.jwt.configs supports the following fields:

Field Required Default Description
issuer_url Yes Expected iss claim for this issuer. Must use https (http allowed only for loopback: localhost, 127.0.0.1, ::1).
jwk_cert_url One of jwk_cert_url / jwk_cert_file JWKS endpoint URL for this issuer's public keys. Must use https (http allowed only for loopback).
jwk_cert_file One of jwk_cert_url / jwk_cert_file Path to a local JWKS file
jwk_cert_ca_file No PEM CA certificate for TLS when fetching jwk_cert_url. Requires jwk_cert_url; ignored with jwk_cert_file only. File must exist in the container.
header No Authorization HTTP header to read the JWT from
audience No "" (any) Expected aud claim; skipped if empty
identity_claim No email JWT claim used as audit identity
identity_claim_pattern No "" (none) Regex the identity value must match; non-matching requests get 401
identity_header No "" (disabled) HTTP header that overrides the JWT claim for audit identity (gateway-set only)

Complete example with all fields:

server:
  jwt:
    enabled: true
    configs:
      - issuer_url: https://idp.example.com/realms/hyperfleet
        jwk_cert_url: https://idp.example.com/realms/hyperfleet/protocol/openid-connect/certs
        jwk_cert_file: ""
        jwk_cert_ca_file: ""
        header: Authorization
        audience: ""
        identity_claim: email
        identity_claim_pattern: ""
        identity_header: ""

JWKS refresh and key rotation

How the API keeps each issuer's keys up to date, so that a signing-key rotation on the identity provider takes effect without restarting the API:

  • Periodic refresh: the JWKS behind jwk_cert_url is re-fetched every 5 minutes. A key removed from the JWKS stops being accepted at the next refresh.
  • Unknown kid: a token whose kid header is not in the cached key set triggers one refresh of that issuer's JWKS. Refreshes are rate limited per issuer: a burst of 3, then one per 30 seconds. Concurrent requests carrying the same unknown kid share that one refresh.
  • Time limit: the 5-second limit covers both the wait for a refresh slot and the refresh request itself. If the next slot is more than 5 seconds away, the request fails immediately with 401. A refresh that takes longer than 5 seconds is abandoned and logged. The key is then picked up by whichever comes first: the next request carrying that kid, which triggers a new refresh as soon as a refresh slot is free, or the next periodic refresh.
  • Still unknown: a token whose kid is still unknown after the refresh is rejected with 401.
  • One issuer per token: a token is only checked against the keys of the issuer named in its iss claim, so it never causes another issuer's JWKS to be fetched or refreshed. A token whose iss matches no configured issuer is rejected as invalid credentials, whatever its expiry.
  • File keys: with jwk_cert_file alone, the keys are read once at startup and never refreshed; changing them needs a restart. With both jwk_cert_file and jwk_cert_url, the file keys always stay valid and the URL keys follow the rules above.
  • CA file: jwk_cert_ca_file is read once at startup. Replacing the CA needs a restart.
  • Startup: each URL is fetched once when the API starts. An unreachable URL does not stop the API from starting, and its keys arrive with the next refresh. A URL that accepts the connection but never answers delays startup until the HTTP timeout: 30 seconds with jwk_cert_ca_file, 60 seconds without.

Creating a service account token

When the API is deployed to a Kubernetes cluster (kind or GKE), create a service account token to authenticate:

# kind
TOKEN=$(kubectl create token default -n hyperfleet-local --audience hyperfleet-api)

# GKE
TOKEN=$(kubectl create token default -n hyperfleet --audience hyperfleet-api)

Kubernetes service account tokens use sub (not email) as the identity claim. The Kubernetes issuer must be configured with identity_claim: sub for caller identity to resolve correctly on mutating requests. See Issuer configuration reference for all fields.

Caller identity for audit

Authentication (JWT validation) and caller identity (audit attribution) are separate concerns. When JWT is enabled, identity resolution is always active because identity_claim defaults to email. Audit fields (created_by, updated_by, deleted_by) are populated from the matched issuer's identity settings. When JWT is disabled, audit fields fall back to system@hyperfleet.local.

Layer Component Responsibility
Outer JWTHandler Validates Authorization: Bearer token
Inner ResolveCallerIdentity middleware Resolves who is recorded as the actor

The resolved identity is written to created_by on create, updated_by on update, and deleted_by on delete. Precedence: per-issuer identity header > JWT claim.

When identity resolution is configured, mutating requests (POST, PATCH, PUT, DELETE) that cannot resolve a caller identity are rejected with 401 Unauthorized. Read requests (GET, LIST) are allowed without identity.

JWT claim (per-issuer)

Configure which JWT claim is used as the caller identity for each issuer:

server:
  jwt:
    configs:
      - issuer_url: https://idp.example.com
        jwk_cert_url: https://idp.example.com/certs
        header: Authorization
        audience: ""
        identity_claim: email   # or preferred_username, sub, etc.
        identity_claim_pattern: ""
        identity_header: ""

HTTP identity header (per-issuer, optional)

When identity_header is set on an issuer config, a trusted gateway can set the caller identity via HTTP header. If the header is present and non-empty, it overrides the JWT claim for audit fields. JWT validation is still required.

server:
  jwt:
    configs:
      - issuer_url: https://idp.example.com
        jwk_cert_url: https://idp.example.com/certs
        header: Authorization
        audience: ""
        identity_claim: email
        identity_claim_pattern: ""
        identity_header: X-HyperFleet-Identity

Security: Clients must not be able to set this header directly. Configure your ingress/gateway to strip the header from external requests and set it from the authenticated upstream user.

Identity values from both sources are validated: trimmed of whitespace, limited to 256 characters, and rejected if they contain control characters.

Gateway authentication (Envoy and Authorino)

In production, HyperFleet API runs behind the Envoy + Authorino gateway (ADR-0020), which authenticates every caller and injects trusted identity and tenant headers. Two caller types use different Authorization schemes:

Caller Scheme Validated by
Human operators Bearer <oidc-jwt> OIDC issuer
Sentinel and adapters (machine) ServiceAccount <k8s-token> Kubernetes TokenReview at the gateway, against a subject allowlist

The ServiceAccount (TokenReview) validation for machine callers happens at the gateway; the API itself does not perform it. The API's in-app JWT middleware accepts the Bearer scheme only and returns 401 Unauthorized ("authorization header does not use Bearer scheme") for anything else.

Note: Because the in-app JWT middleware is Bearer-only, in-app JWT validation and gateway machine authentication cannot both be enabled for machine callers yet — a ServiceAccount token would be rejected by the in-app middleware. Running both is tracked by HYPERFLEET-1484.

Trusted header contract

After authenticating a caller, the gateway injects identity and tenant headers derived from validated claims, and the API treats these as authoritative. This is safe only because Envoy strips any client-supplied copy of these headers before the authorization filter runs, so a client cannot forge them (ADR-0020). It applies to:

  • the tenant system header (server.tenant.system_header, gateway convention X-HyperFleet-System) — value true bypasses tenant scoping, and only the gateway may set it
  • the caller-identity header (per-issuer identity_header, gateway convention X-HyperFleet-Identity) — only consumed when server.jwt.enabled is true; the resolver that reads it is not mounted otherwise, so with JWT disabled the API ignores this header even if tenant scoping is on
  • the tenant dimension headers (server.tenant.dimensions[].header, gateway convention X-HyperFleet-Org, X-HyperFleet-Project, …) — resolved independently of JWT, so these still apply when server.jwt.enabled is false and server.tenant.enabled is true

The API reads whatever header names are configured; the X-HyperFleet-* names are the gateway's convention, not hardcoded. In claims mode (server.tenant.claims_enabled: true) a validated wristband takes precedence and these headers are ignored for tenancy. See Tenant isolation for how these drive scoping.

Tenant isolation

Authentication (JWT validation) and tenant isolation are separate concerns. Tenant identity arrives either as trusted headers injected by a gateway (e.g. Envoy + Authorino), or — in edge+api deployments with server.tenant.claims_enabled: true — from the claims of the signed wristband the gateway issues after authenticating the caller; in claims mode forgeable client headers are ignored. The header path is safe only because the gateway strips client-supplied system/dimension headers, injects validated values, and blocks any direct route to the API pod — see ADR-0020 — Envoy and Authorino as the API Authentication Gateway.

When server.tenant.enabled is true, a resolver middleware reads a system header (grants an unscoped context, e.g. for internal services like Sentinel and adapters) and configured dimension headers (collected into the caller's tenancy map). A caller is treated as a system caller when the system_header value equals true (case-insensitive); in claims mode the hf_system wristband claim plays that role instead. A non-system caller missing a required dimension, presenting an invalid dimension value (values must match ^[A-Za-z0-9._-]+$, at most 63 characters from headers or 255 from claims), or resolving zero dimensions, is rejected with 403 Forbidden before any database access.

Once a tenant context is resolved, resource reads, lists, updates, and deletes are scoped to it (see database.md). A resource outside the caller's tenancy returns 404 Not Found, not 403, on read, update, and delete — this avoids leaking a cross-tenant resource's existence. System callers bypass this scoping entirely, but may only write status/conditions: any other resource mutation (create, update, or delete) from a system identity is rejected with 403 Forbidden.

Configuration

The tenant middleware runs after JWT validation and caller-identity resolution when those are mounted (server.jwt.enabled: true), and is only mounted itself when server.tenant.enabled is true. In gateway-only mode (server.jwt.enabled: false, server.tenant.enabled: true), JWT validation and caller-identity resolution are not mounted at all, and the tenant middleware runs directly off the gateway-injected headers:

server:
  tenant:
    enabled: true
    claims_enabled: false                # true: read dimensions and system identity from the
                                         # validated wristband's claims (edge+api; requires jwt.enabled)
    system_header: X-HyperFleet-System   # value "true" marks system callers that bypass scoping
    dimensions:
      - header: X-HyperFleet-Org         # trusted gateway-injected header
        claim: org_id                    # matching wristband claim (defaults to the key)
        key: org                          # tenancy map key
        required: true
      - header: X-HyperFleet-Project
        claim: project_id
        key: project
        required: false

See Configuration Guide - Tenant Enforcement for the full field reference, environment variables, and validation rules.

Configuration

Environment Variables

# Development (no auth)
export HYPERFLEET_SERVER_JWT_ENABLED=false

# Production (with auth) - configure issuers in config.yaml
export HYPERFLEET_SERVER_JWT_ENABLED=true
# Issuer configs must be set via YAML config file (server.jwt.configs list)

See Deployment for complete configuration options.

Kubernetes Deployment

Configure via Helm values:

# values.yaml — see "Issuer configuration reference" above for all fields
config:
  server:
    jwt:
      enabled: true
      configs:
        - issuer_url: https://your-idp.example.com/auth/realms/your-realm
          jwk_cert_url: https://your-idp.example.com/auth/realms/your-realm/protocol/openid-connect/certs
          audience: https://your-api.example.com

Deploy:

helm install hyperfleet-api oci://quay.io/redhat-services-prod/hyperfleet-tenant/hyperfleet/hyperfleet-api-chart:<tag> --values values.yaml

Note: You may also choose to install from the ./charts folder, if you've cloned this repository locally.

Troubleshooting

Common Issues

401 Unauthorized

  • Check token is valid and not expired
  • Verify issuer_url and audience in server.jwt.configs match token claims
  • Ensure Authorization header is correctly formatted

Token debugging

# Decode JWT token (header and payload only, not verified)
echo $TOKEN | cut -d. -f2 | base64 -d | jq

# Check token expiration
echo $TOKEN | cut -d. -f2 | base64 -d | jq '.exp | todate'

Related Documentation

  • Deployment - Authentication configuration and Kubernetes setup