The SecretString
feature is really nice, and other frameworks do similar things nowadays. However, unlike those other frameworks, Litestar doesn't appear to have the ability to set constraints on this type.
I'd much prefer to use SecretString
over a basic str
for things like passwords, but there are some cases where I'm legally obligated to enforce a minimum length, so this is important.
Using Pydantic as an example, I can do this and it all works just fine:
password: SecretStr = Field(min_length=12, max_length=64)
But when I try to achieve the same thing with Litestar:
password: Annotated[SecretString, Meta(min_length=12, max_length=64)]
I get an error:
TypeError: Can only set `min_length` on a str, bytes, or collection type -
type `typing.Annotated[litestar.datastructures.secret_values.SecretString, msgspec.Meta(min_length=12)]` is invalid
My current workaround feels extremely hacky:
class Signup(Struct):
username: str
password: SecretString
def __post_init__(self):
value = self.password.get_secret()
if len(value) < 12:
raise HTTPException(status_code=400, detail='Passwords must be at least 12 characters.')
if len(value) > 64:
raise HTTPException(status_code=400, detail='Passwords must not be more than 64 characters.')
del value
Ideally I'd be able to encapsulate all of this validation logic into a single field/type definition that I could then reuse multiple places.
It seems to me this feature could only be a good thing.
Is there already a better way to do this than my current workaround?
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too