I am implementing a class that represents a connection to e.g., an API/database, and want to provide a method to reconnect when the connection is lost (e.g., due to a timeout). The user provides a username and a password at initialization, which has to be in raw text due to API requirements.
I think one should NOT store the password in any instance variable; I am aware that one may use the “keyring” library, but was wondering if there is any way that does not depend on external libraries and/or the password cannot be later revealed by any means.
One method I came up with is to use a lambda creator:
class Connection:
def __init__(self, *args, **kwargs):
# other stuff
password = input(“some message”)
self.connection_handle = (lambda pass : (lambda : api.connect(password=pass))(password)
del password
self.conn = self.connection_handle()
def reconnect(self):
self.conn = self.connection_handle()
where for simplicity we assume only password, which is a raw password, is used by some API provided connection procedure api.connect.
I tried inspect.showsource and also examined other attributes of connection_handle. It seemed to me that one cannot find the value of the password anywhere. But I am not entirely sure.
So here are my questions:
Is this lambda creator method really secure in that
passwordcannot be recovered even if one can access the instance of theConnection?Is there any “standard paradigm” to deal with such scenarios when a method needs to be called several times with sensitive argument which one does not wish to store?
Thanks in advance.