Skip to content

Commit

Permalink
Move temporary file deletion into a defer
Browse files Browse the repository at this point in the history
This is required so that the temporary file, which is
potentially sensitive, gets cleaned up even if the function
exits early.

Signed-off-by: Alex Ellis (OpenFaaS Ltd) <[email protected]>
  • Loading branch information
alexellis committed Oct 27, 2023
1 parent 35e3a3a commit f0cdefa
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions cmd/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,14 @@ func mergeConfigs(localKubeconfigPath, context string, k3sconfig []byte) ([]byte
return nil, fmt.Errorf("could not generate a temporary file to store the kubeconfig: %w", err)
}

defer func() {
// Remove the temporarily generated file, even if there is an error and the
// function returns early
if err = os.Remove(file.Name()); err != nil {
log.Printf("could not remove temporary kubeconfig file: %s %s", file.Name(), err)
}
}()

if err := writeConfig(file.Name(), []byte(k3sconfig), context, true); err != nil {
return nil, err
}
Expand Down Expand Up @@ -503,13 +511,6 @@ func mergeConfigs(localKubeconfigPath, context string, k3sconfig []byte) ([]byte
file.Name(), err)
}

// Remove the temporarily generated file
err = os.Remove(file.Name())
if err != nil {
return nil, fmt.Errorf("could not remove temporary kubeconfig file: %s %w",
file.Name(), err)
}

return data, nil
}

Expand Down Expand Up @@ -590,6 +591,8 @@ func loadPublickey(path string) (ssh.AuthMethod, func() error, error) {
return ssh.PublicKeys(signer), noopCloseFunc, nil
}

// rewriteKubeconfig replaces the IP address of the server with the IP address
// it also changes the context from "default" to the value of the --context flag
func rewriteKubeconfig(kubeconfig string, host string, context string) []byte {
if context == "" {
context = "default"
Expand Down

0 comments on commit f0cdefa

Please sign in to comment.