Skip to content
Sarj Code Standards

prefer-secret-field-type

Use Pydantic secret types for credential fields.

Why

Plain credential fields expose their values in model representations and default JSON serialization. SecretStr and SecretBytes mask those values after validation.

Fix

Use SecretStr for text credentials and SecretBytes for byte credentials. Use get_secret_value() at boundaries that need the raw credential and preserve any required wire format explicitly.

Examples

Before — flagged A model exposes its access token
app/models.py
from pydantic import BaseModel
class GoogleTokenResponse(BaseModel):
access_token: str
After — preferred A settings field masks its credential
app/settings.py
from pydantic import SecretStr
from pydantic_settings import BaseSettings
class CloudflareSettings(BaseSettings):
api_token: SecretStr