fix(auth): do not sanitize registration password before hashing

SanitizeForLog is for log output and rewrites tabs/newlines/control
characters. Applying it to req.Password during public registration
changed the credential that was hashed, so login with the original
password failed. Match the invite registration path and pass the
password through unchanged.

Fixes #2521
main
jiahao6635 2026-08-06 18:07:02 +08:00 committed by lyingbug
parent ac9656af1d
commit 9cf8e72ed9
2 changed files with 40 additions and 1 deletions

View File

@ -164,7 +164,12 @@ func (h *AuthHandler) Register(c *gin.Context) {
}
req.Username = secutils.SanitizeForLog(req.Username)
req.Email = secutils.SanitizeForLog(req.Email)
req.Password = secutils.SanitizeForLog(req.Password)
// Password is intentionally NOT sanitized: SanitizeForLog replaces
// \n, \r, \t and strips other control characters so a string is safe
// to write into a log line. Applying it to a real password would
// silently rewrite the credential before hashing, so registration
// would succeed but login with the original password would fail.
// Passwords must never be logged, so they don't need that defence.
// Validate required fields
if req.Username == "" || req.Email == "" || req.Password == "" {

View File

@ -167,3 +167,37 @@ func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
t.Fatalf("nil Auth config must fall back to allow, got %d body=%s", w.Code, w.Body.String())
}
}
// TestRegister_PreservesPasswordBytes is the regression for #2521.
// SanitizeForLog is for log output only; applying it to credentials
// rewrites tabs/newlines/control chars before hashing, so a password
// that registers successfully cannot be used at login.
func TestRegister_PreservesPasswordBytes(t *testing.T) {
// Password contains a tab and a newline — both are rewritten by
// SanitizeForLog (tab → space, newline → space). The handler must
// pass the exact original string to UserService.Register.
const originalPassword = "abc\t123!\nX"
var gotPassword string
us := &stubRegisterUserService{
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
gotPassword = req.Password
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil, nil, nil)
body := validRegisterBody()
body["password"] = originalPassword
w := doRegister(t, newRegisterTestRouter(h), body)
if w.Code != http.StatusCreated {
t.Fatalf("registration with control chars in password must succeed, got %d body=%s",
w.Code, w.Body.String())
}
if gotPassword != originalPassword {
t.Fatalf("password mutated before UserService.Register:\n got %q\n want %q",
gotPassword, originalPassword)
}
}