Recently, I am working on a process that requires create some secret and remove it after it runs successfully. At first, I am planning to store the secret in the memory such that the memory is reclaimed by the operating system when the process terminates and the secret will be destroyed afterwards (theoretically, it is still possible to dump the memory to reclaim it). However, I come across a use case requiring to write the secret on the disk temporarily and share to a sub-process with higher privilege to access it. Here is my problem comes, how can I make sure that my process to do the clean up when my process terminates?
In other languages' implementations, we have to make sure, not only our process does the clean up when it runs successfully (i.e. normal case), while at the same time, we need to make sure all the error handling codes to do the same (i.e. abnormal case). It is a real pain, there is no guarantee that our peer code review can safe guard this, we are all human! Even though, code scanning automation / compilation error detection may not help, as it may be application specific! This use case makes the feature of defer()in Go perfect!
Right after the creation of the secret, we call the defer() function immediately as shown below.
secret, err := GenerateSecret(rand.Reader, 2048)
if err != nil {
log.Fatalf("%v\n", err)
}
// a customized function to write secret to a file
filename, err := writeSecretToFile(secret)
if err != nil {
log.Fatalf("%v\n", err)
}
defer reomveSecretFromFile(filename)
In this way, we can guarantee our function reomveSecretFromFile is called without adding one line of code afterwards.
And the behavior of defer()'s is quite predictable, even we modify the variable filename later in the code, the value of input argument is the value when the defer() is called, not the value when the reomveSecretFromFile is being called.
Reference:
Comments
Post a Comment