System checks (tempest check-config)¶
Validate configuration before serving traffic — empty signing
secret, CORS * with credentials, SQLite in production. A Django-style
check framework: functions inspect your settings and emit messages; the
CLI (or a startup hook) runs them all and fails if any is serious.
The problem¶
A deploy with an empty JWT_SECRET boots happily and only breaks (or
worse, accepts forged tokens) in production. Config errors don't show up
in tests — they depend on the environment. There was no place to declare
"this must be true to ship".
Running the built-in checks¶
The SDK ships checks for the most common slips. Run them against your settings:
The tempest command needs the [cli] extra (or [cli-ops] on a server)
Without either, tempest exits with code 2 and prints how to install it.
In development: uv add --dev "tempest-fastapi-sdk[cli]". Details in
Installation → CLI.
The CLI auto-detects the settings object at conventional locations
(src.core.settings:settings, app.core.settings:settings, …). Point it
explicitly when needed:
Typical output:
WARNING: (security.W004) JWT_SECRET still holds the default declared by its settings field — a deployment that never set it signs tokens with a value that lives in source control.
HINT: Generate one with `tempest secrets rotate`.
INFO: (deployment.I001) SERVER_DEBUG is enabled.
HINT: Ensure SERVER_DEBUG is off in production (it leaks internals).
2 message(s), 0 at/above ERROR.
It exits non-zero when any message reaches --fail-level (default
error) — so it doubles as a CI gate and a pre-deploy check. Raise the
bar to treat warnings as blocking:
Built-in checks (all best-effort — they skip silently when the attribute is absent from your settings):
| id | Level | What |
|---|---|---|
security.W001 / W002 |
WARNING | JWT_SECRET / SECRET_KEY / TOKEN_SECRET empty or < 32 chars |
security.W003 |
WARNING | CORS * with credentials |
security.W004 |
WARNING | secret still equal to the default declared on its own field |
database.W001 |
WARNING | SQLite DATABASE_URL with debug off |
deployment.I001 |
INFO | SERVER_DEBUG (or DEBUG) on |
deployment.I002 |
INFO | bind on 0.0.0.0 |
The secret that passed was the only one guaranteed to be wrong
Up to v0.271.0, security.W002 only rejected a secret shorter than
32 characters — and the placeholder the SDK itself ships in
JWTSettings.JWT_SECRET is exactly 32. A deployment that forgot
to set JWT_SECRET signed tokens with a value published in the SDK
source, and tempest check-config reported everything as fine.
security.W004 compares the value against
model_fields[name].default, never against a copy of the string —
so it keeps holding the day the placeholder changes.
Which field the debug check reads
deployment.I001 and database.W001 resolve debug by name
precedence: SERVER_DEBUG first (the name the ServerSettings
mixin declares), then DEBUG, so a project that declared one by
hand keeps working. Up to v0.271.0 both read only DEBUG — I001
never fired, and database.W001 warned backwards, complaining
about SQLite precisely when debug was on.
Writing your own check¶
A check is a function that receives the context (your settings) and
returns messages. Decorate it with @check:
from tempest_fastapi_sdk.checks import check, error, CheckMessage
@check("security")
def stripe_key_present(settings: object) -> list[CheckMessage]:
"""Fail the deploy if the Stripe key is not configured."""
if not getattr(settings, "STRIPE_API_KEY", ""):
return [
error(
"STRIPE_API_KEY is not set.",
hint="Export it before deploying the billing service.",
id="billing.E001",
)
]
return []
The debug / info / warning / error / critical constructors
build a CheckMessage at the right level. The tag ("security") lets
you run a subset:
Checks must be imported to register
@check registers on module import. The CLI imports your settings
(and whatever they import), so checks defined next to the settings
load themselves. For standalone modules, use --import:
Failing fast at startup¶
Run the checks in the lifespan so a misconfigured deploy does not serve traffic:
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator
from fastapi import FastAPI
from tempest_fastapi_sdk.checks import run_system_checks, SystemCheckError
from src.core.settings import settings
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
try:
run_system_checks(settings) # raises on ERROR+
except SystemCheckError as exc:
# log exc.messages and abort the boot
raise
yield
run_system_checks raises SystemCheckError when any message reaches
fail_level (default ERROR); run_checks does the same but only
returns the list, without raising.
Production guard: EnvironmentSettings¶
The checks above warn. For what must never reach production — SQLite,
the placeholder JWT_SECRET, CORS * — a warning is not enough: the deploy
has to fail. That is what the EnvironmentSettings mixin does. It adds the
ENV field (development, test or production) and, with
ENV=production, refuses to build the settings while any composed mixin
still holds a development value:
import os
from pydantic import ValidationError
from tempest_fastapi_sdk import (
BaseAppSettings,
DatabaseSettings,
EnvironmentSettings,
JWTSettings,
ServerSettings,
)
class Settings(
EnvironmentSettings,
ServerSettings,
DatabaseSettings,
JWTSettings,
BaseAppSettings,
):
"""Service settings, with the production guard."""
os.environ["ENV"] = "production"
try:
Settings()
except ValidationError as exc:
print(exc)
With neither DATABASE_URL nor JWT_SECRET in the environment, the output
lists every field at once — by name, never by value:
1 validation error for Settings
Value error, ENV=production refuses development values:
- DATABASE_URL: points at SQLite (the development default)
- JWT_SECRET: still the public placeholder declared by JWTSettings [type=value_error]
With ENV=development or ENV=test, the guard does not run.
ENV has no default. Forgetting the variable fails the boot instead of
starting as development:
Up to 0.341.0 the default was development, and a production host without
ENV booted with SQLite, the placeholder JWT_SECRET and an empty
TOKEN_SECRET without the guard ever running. A test suite pins its own
value (os.environ["ENV"] = "test" in conftest.py, before importing the
app).
ENV=test does not read the .env¶
A suite pins ENV=test precisely so it does not inherit the environment of
whoever runs it. So when ENV=test comes from the process environment
or from the constructor (Settings(ENV="test")), EnvironmentSettings
removes the .env from the sources: only what the test passed, the
exported variables and the defaults apply.
import os
from pathlib import Path
from tempest_fastapi_sdk import BaseAppSettings, EnvironmentSettings
class Settings(EnvironmentSettings, BaseAppSettings):
SMTP_HOST: str = "localhost"
Path(".env").write_text("ENV=development\nSMTP_HOST=smtp.dev.example.com\n")
print(Settings().SMTP_HOST)
os.environ["ENV"] = "test"
print(Settings().SMTP_HOST)
The first Settings() reads ENV and SMTP_HOST from the .env; the
second, with ENV=test exported, does not open the file.
ENV=test written only in the .env does not discard the .env
The decision looks only at the constructor and the process environment.
An ENV=test that lives inside the .env is read like any other
value, and the rest of the file applies with it: the file cannot be the
reason it is ignored. For an isolated suite, export ENV=test in
conftest.py, before importing the app.
Overrode settings_customise_sources?
The discard lives in that hook. A Settings that overrides it calls
super().settings_customise_sources(...) to keep the behaviour.
What each mixin refuses¶
The guard only looks at the mixins you compose. Each one declares its own
rules in its production_violations() method:
| Mixin | Refused in production |
|---|---|
ServerSettings |
SERVER_DEBUG=true, SERVER_RELOAD=true |
DatabaseSettings |
a DATABASE_URL with a sqlite dialect |
JWTSettings |
JWT_SECRET equal to the default the mixin declares |
CORSSettings |
"*" in CORS_ORIGINS; with CORS_ALLOW_CREDENTIALS=true, also "null" in CORS_ORIGINS and a CORS_ORIGIN_REGEX that matches a reserved .invalid origin (.*, https://.*; a partly anchored regex such as https://.*example\.com is not detected) — Starlette echoes the caller's own Origin with Access-Control-Allow-Credentials: true |
TokenSettings |
an empty TOKEN_SECRET (the X-Token gate would only pass with allow_unauthenticated=True) |
TaskIQSettings |
an empty TASKIQ_BROKER_URL (falls back to the in-memory broker) |
KafkaSettings |
KAFKA_SECURITY_PROTOCOL=SASL_PLAINTEXT with the PLAIN mechanism (the password crosses the network unencrypted); an empty KAFKA_SASL_PASSWORD under a SASL_* protocol |
StorageSettings |
the default minioadmin keys, STORAGE_SECURE=false (except a private bucket behind an HTTPS public endpoint — see Storage), an explicit STORAGE_PUBLIC_SECURE=false |
EmailSettings |
a mailpit/mailhog host, loopback on port 1025, the default SMTP_HOST with no SMTP_USERNAME, the default SMTP_FROM_ADDR or one on a reserved domain |
RevenueCatSettings |
both webhook secrets empty |
AuthSettings |
AUTH_AUTO_ACTIVATE=true and AUTH_RETURN_TOKEN_IN_RESPONSE=true (always); an e-mail link template (AUTH_*_URL_TEMPLATE) on a local/reserved host or plain http:// (with e-mail on) |
The placeholder comes from the mixin, not from a literal
JWT_SECRET is compared with JWTSettings.model_fields["JWT_SECRET"].default.
If the default changes, the check follows it.
Adding (or waiving) a rule¶
production_violations() is cooperative: override it on your Settings,
call super() and work on the list. That is how you add a rule of the
service — or drop one you accepted on purpose, like SQLite on a single-node
service:
import os
from pydantic import Field, ValidationError
from tempest_fastapi_sdk import BaseAppSettings, DatabaseSettings, EnvironmentSettings
class Settings(EnvironmentSettings, DatabaseSettings, BaseAppSettings):
"""Single-node service: SQLite in production is a decision already made."""
PUBLIC_URL: str = Field(default="http://localhost:8000")
def production_violations(self) -> list[str]:
"""Accept SQLite and require HTTPS on the public URL.
Returns:
list[str]: The mixins' violations, minus SQLite, plus the
service's own rule.
"""
violations: list[str] = [
entry
for entry in super().production_violations()
if not entry.startswith("DATABASE_URL:")
]
if not self.PUBLIC_URL.startswith("https://"):
violations.append("PUBLIC_URL: not HTTPS")
return violations
os.environ["ENV"] = "production"
try:
Settings()
except ValidationError as exc:
print(exc)
os.environ["PUBLIC_URL"] = "https://api.example.com"
print(Settings().ENV)
1 validation error for Settings
Value error, ENV=production refuses development values:
- PUBLIC_URL: not HTTPS [type=value_error]
production
A validation error does not print the environment
BaseAppSettings now sets hide_input_in_errors=True. On a
BaseSettings the input of an error is the whole environment — a
missing required field used to print input_value={'JWT_SECRET': ...}
into the boot traceback. Now the message carries only the field and the
reason. Set hide_input_in_errors in your own model_config to get the
input back.
Switching integrations on and off (phased deploys)¶
Not every service reaches production with everything ready. The database and the JWT are configured, but the S3 bucket, SMTP and the Firebase account arrive in a later phase. Left alone, the guard refuses the boot over integrations you don't even use yet — and the temptation is to fill in fake values just to get past it, which is exactly what the guard exists to prevent.
The explicit way out is one switch per integration:
| Mixin | Switch | Default |
|---|---|---|
StorageSettings |
STORAGE_ENABLED |
true |
EmailSettings |
EMAIL_ENABLED |
true |
FirebaseSettings |
FIREBASE_ENABLED |
true |
RevenueCatSettings |
REVENUECAT_ENABLED |
true |
With a switch set to false, three things happen, always together:
- The guard skips that mixin's rules — the boot succeeds.
- The integration's name shows up in
settings.disabled_integrations(), for you to log at boot or show in readiness. Switching off is never invisible. - The client built from the same settings refuses every call with
503 INTEGRATION_DISABLED, instead of trying to reach the development default.
A production .env with the database and JWT ready, and the rest off:
ENV=production
DATABASE_URL=postgresql+asyncpg://app:s3nha@db:5432/app
JWT_SECRET=replace-with-a-real-long-secret-0123456789abcdef
STORAGE_ENABLED=false
EMAIL_ENABLED=false
FIREBASE_ENABLED=false
And the service, without a single if on the switches — the same
construction line as always:
import logging
from fastapi import FastAPI
from fastapi.testclient import TestClient
from tempest_fastapi_sdk import (
AsyncMinIOClient,
BaseAppSettings,
DatabaseSettings,
EmailSettings,
EmailUtils,
EnvironmentSettings,
FirebaseSettings,
JWTSettings,
StorageSettings,
register_exception_handlers,
)
logger = logging.getLogger("app")
class Settings(
EnvironmentSettings,
DatabaseSettings,
JWTSettings,
StorageSettings,
EmailSettings,
FirebaseSettings,
BaseAppSettings,
):
"""Service settings: database and JWT ready, the rest not yet."""
settings = Settings()
print("disabled:", sorted(settings.disabled_integrations()))
print("mobile push:", settings.firebase_enabled)
storage = AsyncMinIOClient(**settings.storage_kwargs())
mailer = EmailUtils(**settings.email_kwargs())
app = FastAPI()
register_exception_handlers(app)
@app.post("/avatar")
async def upload_avatar() -> dict[str, str]:
"""Store the avatar in the bucket."""
await storage.put_object("avatar.png", b"\x89PNG")
return {"status": "ok"}
response = TestClient(app).post("/avatar")
print(response.status_code, response.json())
The boot succeeds, and the route that uses the bucket answers 503
naming the integration:
disabled: ['email', 'firebase', 'storage']
mobile push: False
503 {'detail': 'The storage integration is disabled in this environment', 'code': 'INTEGRATION_DISABLED', 'details': {'integration': 'storage'}}
Flip STORAGE_ENABLED=false to true without configuring the bucket,
and the boot fails again, as before:
- STORAGE_ACCESS_KEY: still the MinIO default credential
- STORAGE_SECRET_KEY: still the MinIO default credential
- STORAGE_SECURE: storage traffic over plain HTTP (allowed only for a private STORAGE_ENDPOINT behind an HTTPS STORAGE_PUBLIC_ENDPOINT) [type=value_error]
What each integration does when switched off:
| Integration | Construction | In use |
|---|---|---|
storage |
AsyncMinIOClient(**settings.storage_kwargs()) receives enabled=False; no minio client is created (or imported) |
every operation — the client attribute included — raises IntegrationDisabledException; a SubjectObjectStorage on top inherits the refusal |
email |
EmailUtils(**settings.email_kwargs()) receives enabled=False; the [email] extra is not required |
send and send_many raise IntegrationDisabledException before building the message; render_template keeps working |
firebase |
settings.firebase_enabled (and PushSettings.mobile_enabled) becomes False; firebase_kwargs() returns only {"enabled": False} |
FirebaseAuth initializes no app and answers 503 from verify and the dependencies; an FCMTransport on top claims no platform: mobile push is discarded (the DeviceService skips the device) and the transport logs one warning when built |
revenuecat |
only the guard and disabled_integrations() change |
the webhook keeps reading its own secrets: with both empty it keeps refusing every delivery with 401 |
The enabled key only appears with the integration off
storage_kwargs() and email_kwargs() add enabled=False only
when the switch is false. With the default the dictionary is exactly
what it was — code that splats it into its own class does not break
on upgrade.
E-mail switched on gained a production rule
With EMAIL_ENABLED=true and ENV=production, the guard now refuses
what can only be a development setup: an SMTP_HOST whose first label
is mailpit or mailhog; SMTP_PORT=1025 together with a loopback
host (localhost, 127.0.0.1, ::1) — the port Mailpit publishes and
the one tempest new writes; SMTP_HOST still at its declared default
(localhost) with no SMTP_USERNAME; and an SMTP_FROM_ADDR equal to
the declared default, empty,
has no @, or uses a reserved domain (example.com, example.net,
example.org, localhost and their subdomains, or anything under .example, .invalid,
.localhost, .test). The default noreply@example.com is on that
list. A local relay (Postfix forwarding to the provider) keeps
booting with SMTP_USERNAME set, or addressed as 127.0.0.1 on a port
other than 1025. Gmail (smtp.gmail.com:587, STARTTLS, an app
password in SMTP_USERNAME/SMTP_PASSWORD, a real sender) passes with
no violation. A
service that composes EmailSettings without configuring SMTP now
needs EMAIL_ENABLED=false to boot in production.
The auth flow honours the e-mail switch too: with EmailUtils(enabled=False)
wired into UserAuthService, every make_auth_router route that would
send a link answers 503 INTEGRATION_DISABLED before writing
anything — see Auth flow.
Recap¶
tempest check-configruns the checks against your settings; exits non-zero at--fail-level(defaulterror).- Built-ins cover secret, CORS, SQLite-in-prod, DEBUG, bind.
@check("tag")registers your own;debug/info/warning/error/criticalbuild the message.run_system_checks(settings)in the lifespan aborts a misconfigured boot.EnvironmentSettingswithENV=productionstops the boot while a composed mixin still holds a development value, listing the fields without printing values;production_violations()+super()adds or waives a rule.STORAGE_ENABLED,EMAIL_ENABLED,FIREBASE_ENABLEDandREVENUECAT_ENABLEDset tofalseswitch the integration off: the guard skips it,disabled_integrations()names it, and the client built from the settings answers503 INTEGRATION_DISABLEDon every call.