On Wed, 2021-08-04 at 14:14 -0700, S Pradeep Kumar wrote:
Setting aside the question of whether it can easily be determined whether a given string is a literal or not (I don't know, but would be interested in knowing the answer)...
As per PEP 586:
Literal types indicate that a variable has a specific and concrete value. For example, if we define some variable foo to have type Literal[3], we are declaring that foo must be exactly equal to 3 and no other value.
Right, so we're on the same page, want to confirm that should be no rule dictating how 3 was arrived at. It could have been the result of addition. I expect Literal["aaa", "bbb"] would currently accept the string "aaa" regardless of whether it was "a"*3 , "a" + "aa", or "aaa".
In practice, a typechecker will consider a string to be a literal string if it is in quotes. Performing an operation like appending a string will make the typechecker no longer treat it as a literal string. Here is an example [1]. So, a malicious string dynamically assembled (by appending, etc.) will not be treated as a literal string and will be flagged by the typechecker when passed to something that expects `Literal[str]`. I hope that makes sense.
It makes sense. I'm still dubious about the benefits though.
Note that `eval` is typed as returning `Any`, which means we loses all safety, so that's a whole different problem :) The security use cases I was talking about were innocuous inputs that happened to be user-controlled, such as a field in a request JSON that got passed or appended to the format string or shell command function.
1. I think passing or appending a format string from user input is (or should be!) a security anti-pattern, just like you should also not eval raw user input. This strikes me as more a job for a source code vulnerability scanner rather than a static type checking library. 2. If the consensus is that this proposal has enough merit to be added, my request would be to allow for the detection of a string's "literalness" at runtime, not just through graphing it in a static type checker.