Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Purpose of Pydantic's SecretStr?

I am learning the Pydantic module, trying to adopt its features/benefits via a toy FastAPI web backend as an example implementation.

I chose to use Pydantic's SecretStr to "hide" passwords. I know it is not really secure, and I am also using passlib for proper password encryption in DB storage (and using HTTPS for security in transit).

But this got me thinking: if there is no real security to SecretStr, what is its purpose?

I don't mean for this to sound inflammatory; Pydantic does not claim that the Secret Types are secure. The only claim they provide is this:

You can use the SecretStr and the SecretBytes data types for storing sensitive information that you do not want to be visible in logging or tracebacks.

But I do not understand this: how does SecretStr help in hiding logging or tracebacks? Can't I just make sure not to log the password at all?


Can someone provide an explanation + example to help me better understand when and how it can be helpful? I am struggling to find its real purpose... and if there is no benefit, then it is better to just use an str for the model/schema instead of SecretStr.

like image 741
Mike Williamson Avatar asked Nov 26 '25 16:11

Mike Williamson


1 Answers

You already answered a big part of the question yourself.

You can use the SecretStr and the SecretBytes data types for storing sensitive information that you do not want to be visible in logging or tracebacks.

I would like to add another benefit.

Developers are constantly reminded that they are working with secrets because they need to invoke .get_secret_value() to read the real value.

We might consider this as syntactic salt (analog to syntactic sugar which makes things easier). Syntactic salt makes things harder to mess up. If you would try to send a SecretStr in a response model in e.g. FastAPI, you'd need to proactively enable that functionality.

From the docs:

class SimpleModelDumpable(BaseModel):
    password: SecretStr

    class Config:
        json_encoders = {
            SecretStr: lambda v: v.get_secret_value() if v else None
         }
like image 149
ctholho Avatar answered Nov 29 '25 06:11

ctholho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!