In Pydantic 2, what does typing a settings field as SecretStr keep out of logs, and where can the secret still leak?
answer
- masked repr and str
- JSON dump shows stars
- explicit unwrap to read
- errors can echo inputs
basics
~10 sSecretStr masks the value as ********** in repr, str and JSON dumps, so printing settings is safe; the secret still leaks through get_secret_value() output you log, ValidationError input values, and the settings debug log.
solid answer
~40 sA `SecretStr` field wraps the string so `repr()` and `str()` show `'**********'` (or `''` when empty). Printing the settings object shows `database_password=SecretStr('**********')`; `model_dump()` returns the `SecretStr` object itself, and `model_dump_json()` or `model_dump(mode="json")` writes `"**********"`. Code must call `get_secret_value()` to get the real string, which makes every use explicit. It is masking, not encryption: the plain value is in memory, and anything you build from `get_secret_value()`, such as a connection string, is an ordinary `str` that logs in full. Other leak paths are `ValidationError` messages, which print `input_value` unless `hide_input_in_errors=True`, the `PYDANTIC_SETTINGS_DEBUG` log, which prints raw source values, and a `field_serializer` that unwraps the secret on purpose.
code
python · 17 linesfrom pydantic import SecretStr
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_password: SecretStr
settings = Settings(database_password="s3cr3t")
print(settings)
# database_password=SecretStr('**********')
print(settings.model_dump())
# {'database_password': SecretStr('**********')}
print(settings.model_dump_json())
# {"database_password":"**********"}
print(settings.database_password.get_secret_value())
# s3cr3tgo deeper
Remember that SecretStr prints as ten asterisks and that get_secret_value() is the only way to read it.
Explain what model_dump and model_dump_json each produce for a secret, why JSON does not round-trip it, and how hide_input_in_errors closes the error path.
Audit the leak paths that remain: derived strings, validation errors on raw input, the settings debug log and unwrapping serializers, and close each one in code review.
Treat SecretStr as a guard against accidental display, not as secret management, and decide where a team's real protection lives: logging policy, error reporting and how secrets reach the process.
## What SecretStr is `SecretStr` is a Pydantic type for **strings you do not want to see in logs or tracebacks**. You use it as a field type, `database_password: SecretStr`, and Pydantic validates the input as a string and wraps it in a `SecretStr` object. It works on any model, but it matters most on a `BaseSettings` class, because settings objects get printed: in startup logs, in debugging sessions, in error reports. ## Where the value is masked When the value is non-empty, the wrapper hides it everywhere Pydantic controls the output: | Operation | Output for `SecretStr("s3cr3t")` | |---|---| | `repr(value)` | `SecretStr('**********')` | | `str(value)` or an f-string | `**********` | | `print(settings)` | `database_password=SecretStr('**********')` | | `settings.model_dump()` | `{'database_password': SecretStr('**********')}` | | `settings.model_dump_json()` | `{"database_password":"**********"}` | | `settings.database_password.get_secret_value()` | `s3cr3t` | An empty secret is displayed as `''` rather than stars. In JSON Schema output the field is marked `writeOnly` with `format: password`. Two consequences are easy to miss: - `model_dump()` in Python mode does **not** turn the secret into a string; it hands back the `SecretStr` object; - a JSON dump writes the **stars**, so dumping settings to JSON and reading them back does not round-trip the secret. To emit the plain value on purpose, add a `field_serializer` that calls `get_secret_value()`, ideally with `when_used="json"` so only JSON output is affected. ## Reading the real value `get_secret_value()` is the only way to unwrap it. That is the point of the design: every place that needs the secret has to say so, and a code review can search for those calls. Two `SecretStr` objects compare equal when their secret values are equal. ## Where the secret still leaks `SecretStr` protects the **object**. It does not follow the value once you take it out, and it does not change how other parts of the library report inputs: 1. **Derived strings.** `f"postgresql://app:{pw.get_secret_value()}@db/orders"` is a plain `str`; log it and the password is in the log. 2. **Validation errors.** A `ValidationError` prints `input_value` for each error. If a nested database block arrives as a dict without a required key, the `missing` error prints that whole dict, password included, because at that point it is raw input, not yet a `SecretStr`. Setting `hide_input_in_errors=True` in the class's `model_config` removes input values and types from error messages. 3. **The settings debug log.** `PYDANTIC_SETTINGS_DEBUG=1` logs every source's raw values at `DEBUG` level. The documentation warns it may contain secrets and should not be left on in production. 4. **Deliberate serializers.** A `field_serializer` that unwraps the value, or any code that copies `get_secret_value()` into a plain `str` field elsewhere, removes the protection. 5. **Process memory.** The value sits unencrypted in memory, so a heap dump or debugger shows it. `SecretStr` is about accidental display, not about protecting a compromised process. ## A worked example ```python from pydantic import SecretStr from pydantic_settings import BaseSettings class Settings(BaseSettings): database_password: SecretStr settings = Settings(database_password="s3cr3t") print(settings) # database_password=SecretStr('**********') print(settings.model_dump_json()) # {"database_password":"**********"} print(settings.database_password.get_secret_value()) # s3cr3t ``` ## Practical rules for a settings class - Type every password, token and key as `SecretStr`, including fields inside nested sub-models, so printing any part of the settings tree stays masked. - Unwrap with `get_secret_value()` at the last moment, inside the call that needs it, and never store the result in a long-lived plain attribute. - Set `hide_input_in_errors=True` on the settings class so a startup failure cannot print raw input. - Keep `PYDANTIC_SETTINGS_DEBUG` off outside a trusted debugging session. - Do not use a JSON dump of settings as a way to pass configuration to another process; the secrets arrive as asterisks. - Search code review diffs for `get_secret_value()`; each new call is a place the value leaves its wrapper. ## Related types `SecretBytes` does the same for `bytes`, and the generic `Secret[T]` wraps other types such as `Secret[int]`. Where secrets come from, a secret file, an environment variable or a `.env` entry, does not change any of this: masking starts once the value has been validated into the field.
- How do you stop a startup ValidationError from printing a password the environment supplied?Set `hide_input_in_errors=True` in the settings class's `model_config`. Pydantic then prints each error's location, message and type but leaves out `input_value` and `input_type`. Without it, an error on a nested block can print the raw dict it received, and the password with it, because the value has not yet become a `SecretStr`.
- Why does dumping settings to JSON and loading them back lose the password?In JSON mode the `SecretStr` serializer writes `"**********"`, not the value, so the reloaded object holds ten asterisks. If a JSON round trip is genuinely needed, add a `field_serializer` that returns `get_secret_value()`, ideally limited with `when_used="json"`, and treat that output as sensitive.
- SecretStr encrypts the value in memory.
- model_dump() turns a SecretStr into its plain string value.
- Once a field is SecretStr, validation errors can never reveal it.
- Calling str() on a SecretStr returns the real secret.
- A connection string built from get_secret_value() is still masked when logged.