Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

length validation of bytes fields incorrectly converts to utf-8 string #1261

Open
immesys opened this issue Jun 10, 2024 · 0 comments · May be fixed by #1296
Open

length validation of bytes fields incorrectly converts to utf-8 string #1261

immesys opened this issue Jun 10, 2024 · 0 comments · May be fixed by #1296
Labels
bug Something isn't working

Comments

@immesys
Copy link

immesys commented Jun 10, 2024

What version of ogen are you using?

v1.2.1

Can this issue be reproduced with the latest version?

Yes

What did you do?

I have a field in an API object with format: bytes and a length requirement:

        key:
          type: string
          format: byte
          minLength: 256

This is generating code that looks like this in oas_validators_gen.go

func (s *KeyInfo) Validate() error {
	var failures []validate.FieldError
	if err := func() error {
		if err := (validate.String{
			MinLength:    256,
			MinLengthSet: true,
			MaxLength:    0,
			MaxLengthSet: false,
			Email:        false,
			Hostname:     false,
			Regex:        nil,
		}).Validate(string(s.Key)); err != nil {
			return errors.Wrap(err, "string")
		}
		return nil
	}(); err != nil {
		failures = append(failures, validate.FieldError{
			Name:  "key",
			Error: err,
		})
	}
	if len(failures) > 0 {
		return &validate.Error{Fields: failures}
	}
	return nil
}

This converts the byte array to a string and uses the string validator, which counts runes for length, not bytes:

func (t String) Validate(v string) error {
	if err := (Array{
		MinLength:    t.MinLength,
		MinLengthSet: t.MinLengthSet,
		MaxLength:    t.MaxLength,
		MaxLengthSet: t.MaxLengthSet,
	}).ValidateLength(len([]rune(v))); err != nil {
		return err
	}

Thus, this code is incorrect: there is no guarantee that this byte array is valid utf-8. In fact it is not, so I consistently get errors that the key is too short because it is counting utf-8 runes rather than counting bytes.

What did you expect to see?

I would expect validation of format: bytes fields to be done over bytes, not converting to utf-8 runes

What did you see instead?

I see consistently incorrect length validation for format: bytes fields

@immesys immesys added the bug Something isn't working label Jun 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant