Enhancement: Be able to enforce `min_length`, `max_length`, etc. for `SecretString`
bdoms opened this issue · 1 comments
Summary
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.
Basic Example
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.
Drawbacks and Impact
It seems to me this feature could only be a good thing.
Unresolved questions
Is there already a better way to do this than my current workaround?
Note
While we are open for sponsoring on GitHub Sponsors and
OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.
Check out all issues funded or available for funding on our Polar.sh dashboard
- If you would like to see an issue prioritized, make a pledge towards it!
- We receive the pledge once the issue is completed & verified
- This, along with engagement in the community, helps us know which features are a priority to our users.