Отвечать 400 и 401 вместо 500 на NUL и невалидный UTF-8 во входных данных

This commit is contained in:
2026-10-06 15:41:36 +03:00
parent 8f9252a5c1
commit 3001507ecb
10 changed files with 34 additions and 5 deletions
+7
View File
@@ -45,7 +45,14 @@ var dummyHash = sync.OnceValue(func() string {
// Authenticate returns the user whose password matches, or
// ErrInvalidCredentials for an unknown username and a wrong password alike.
// The username comes straight from the Basic header, so one that cannot
// exist (including NUL or invalid UTF-8, which the database would reject)
// is answered without a query, but after the same KDF work.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
if !usernamePattern.MatchString(username) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
u, err := s.repo.GetByUsername(ctx, username)
if errors.Is(err, ErrNotFound) {
_, _ = password.Verify(dummyHash(), plain)
+7 -1
View File
@@ -172,7 +172,13 @@ func TestAuthenticateFailuresLookTheSame(t *testing.T) {
}
_, wrong := svc.Authenticate(ctx, "alice", pw+"!")
_, unknown := svc.Authenticate(ctx, "nobody", pw)
for name, err := range map[string]error{"wrong password": wrong, "unknown user": unknown} {
// Basic credentials are client bytes: a username the database cannot
// even compare must still be a plain credential failure.
_, nul := svc.Authenticate(ctx, "a\x00b", pw)
_, notUTF8 := svc.Authenticate(ctx, "\xff\xfe", pw)
for name, err := range map[string]error{
"wrong password": wrong, "unknown user": unknown, "nul username": nul, "invalid utf-8 username": notUTF8,
} {
if !errors.Is(err, user.ErrInvalidCredentials) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
+4
View File
@@ -51,6 +51,10 @@ func New(id uuid.UUID, username, displayName string) (User, error) {
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(displayName, 0) {
return User{}, apperr.Invalid("display_name must not contain the NUL character")
}
return User{
ID: id,
Username: username,
+1 -1
View File
@@ -68,7 +68,7 @@ func TestNewValidatesDisplayNameByCodePoints(t *testing.T) {
t.Errorf("display_name %q must be accepted: %v", name, err)
}
}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101)}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101), "nul\x00inside"}
for _, name := range invalid {
_, err := user.New(ident.New(), "alice", name)
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "display_name") {