go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

Nil pointer dereference with Errors.Error() #147

Open voroskoi opened 3 years ago

voroskoi commented 3 years ago

Hi,

Thank You for this library, it is amazing.

I have found a bug, here is the reproducer:

package main

import (
    validation "github.com/go-ozzo/ozzo-validation/v4"
)

type User struct {
    Login string
}

func main() {
    u := User{
        Login: "blah",
    }

    u.Validate()
}

func (u User) Validate() error {
    Err := validation.Errors{
        "Login": validation.Validate(u.Login, validation.Required),
    }
    _ = Err.Error()
    return Err.Filter()
}

Calling Err.Error() cases panic because of a nil pointer dereference.

Below the suggested fix:

From 34a1f17ee23bb604c93a5d67aa83581f837f2d5a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?V=C3=96R=C3=96SK=C5=90I=20Andr=C3=A1s?= <voroskoi@gmail.com>
Date: Wed, 21 Apr 2021 22:15:41 +0200
Subject: [PATCH] Fix nil pointer reference in Errors.Error() method

---
 error.go | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/error.go b/error.go
index e75b1de..4284f51 100644
--- a/error.go
+++ b/error.go
@@ -128,6 +128,9 @@ func (es Errors) Error() string {

    var s strings.Builder
    for i, key := range keys {
+       if es[key] == nil {
+           continue
+       }
        if i > 0 {
            s.WriteString("; ")
        }
-- 
2.29.2.windows.3

Thank You!