Skip to content

Commit

Permalink
WIP: Add temporary file when changing htpasswd password
Browse files Browse the repository at this point in the history
  • Loading branch information
onidoru committed Feb 2, 2024
1 parent 1081018 commit b79b823
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
33 changes: 26 additions & 7 deletions pkg/api/htpasswd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"sync"

Expand Down Expand Up @@ -110,10 +111,7 @@ func (hc *HtpasswdClient) ChangePassword(login, supposedOldPassword, newPassword
return zerr.ErrPasswordIsEmpty
}

hc.credMap.rw.RLock()
oldPassphrase, ok := hc.credMap.m[login]
hc.credMap.rw.RUnlock()

oldPassphrase, ok := hc.credMap.Get(login)
if !ok {
return zerr.ErrBadUser
}
Expand Down Expand Up @@ -151,10 +149,31 @@ func (hc *HtpasswdClient) ChangePassword(login, supposedOldPassword, newPassword
}
}

// write new content to file
output := strings.Join(lines, "\n")
// write new content to temporary file
// and replace the old file with temporary, so the operation is atomic
output := []byte(strings.Join(lines, "\n"))

tmpfile, err := os.CreateTemp(filepath.Dir(hc.filepath), "htpasswd-*.tmp")
if err != nil {
return fmt.Errorf("error occurred when creating temp htpasswd file: %w", err)
}

if _, err := tmpfile.Write(output); err != nil {
tmpfile.Close()
os.Remove(tmpfile.Name())
return fmt.Errorf("error occurred when writing to temp htpasswd file: %w", err)
}

if err := tmpfile.Close(); err != nil {
os.Remove(tmpfile.Name())
return fmt.Errorf("error occurred when closing temp htpasswd file: %w", err)
}

if err := os.Rename(tmpfile.Name(), hc.filepath); err != nil {
return fmt.Errorf("error occurred while replacing htpasswd file with new file: %w", err)
}

err = os.WriteFile(hc.filepath, []byte(output), constants.DefaultDirPerms)
err = os.WriteFile(hc.filepath, output, constants.DefaultDirPerms)
if err != nil {
return fmt.Errorf("error occurred while writing to creds-file: %w", err)
}
Expand Down
4 changes: 3 additions & 1 deletion pkg/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2248,14 +2248,16 @@ func (rh *RouteHandler) ChangePassword(resp http.ResponseWriter, req *http.Reque

userAc, err := reqCtx.UserAcFromContext(req.Context())
if err != nil {
resp.WriteHeader(http.StatusNotFound)
resp.WriteHeader(http.StatusInternalServerError)

return
}

username := userAc.GetUsername()
if username == "" {
resp.WriteHeader(http.StatusNotFound)

return
}

if err := rh.c.HtpasswdClient.ChangePassword(username, reqBody.OldPassword, reqBody.NewPassword); err != nil {
Expand Down

0 comments on commit b79b823

Please sign in to comment.