/
document_validation.go
174 lines (140 loc) · 4.67 KB
/
document_validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"errors"
"fmt"
"math"
"strings"
"unicode/utf8"
"github.com/FerretDB/FerretDB/internal/util/must"
)
//go:generate ../../bin/stringer -linecomment -type ValidationErrorCode
// ValidationErrorCode represents ValidationData error code.
type ValidationErrorCode int
const (
_ ValidationErrorCode = iota
// ErrValidation indicates that document is invalid.
ErrValidation
// ErrWrongIDType indicates that _id field is invalid.
ErrWrongIDType
// ErrIDNotFound indicates that _id field is not found.
ErrIDNotFound
)
// ValidationError describes an error that could occur when validating a document.
type ValidationError struct {
code ValidationErrorCode
reason error
}
// newValidationError creates a new ValidationError.
func newValidationError(code ValidationErrorCode, reason error) error {
return &ValidationError{reason: reason, code: code}
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.reason.Error()
}
// Code returns the ValidationError code.
func (e *ValidationError) Code() ValidationErrorCode {
return e.code
}
// ValidateData checks if the document represents a valid "data document".
// It places `_id` field into the fields slice 0 index.
// It replaces negative zero -0 with valid positive zero 0.
// If the document is not valid it returns *ValidationError.
func (d *Document) ValidateData() error {
return d.validateData(true)
}
// validateData applies different validation rules to the `_id` field depending on the document level.
func (d *Document) validateData(isTopLevel bool) error {
d.moveIDToTheFirstIndex()
keys := d.Keys()
values := d.Values()
duplicateChecker := make(map[string]struct{}, len(keys))
var idPresent bool
for i, key := range keys {
// integration tests for those cases are in the `dance` repo
if !utf8.ValidString(key) {
return newValidationError(ErrValidation, fmt.Errorf("invalid key: %q (not a valid UTF-8 string)", key))
}
if strings.HasPrefix(key, "$") {
return newValidationError(ErrValidation, fmt.Errorf("invalid key: %q (key must not start with '$' sign)", key))
}
if strings.Contains(key, ".") {
return newValidationError(ErrValidation, fmt.Errorf("invalid key: %q (key must not contain '.' sign)", key))
}
if _, ok := duplicateChecker[key]; ok {
return newValidationError(ErrValidation, fmt.Errorf("invalid key: %q (duplicate keys are not allowed)", key))
}
duplicateChecker[key] = struct{}{}
if key == "_id" {
idPresent = true
}
value := values[i]
switch value := value.(type) {
case *Document:
err := value.validateData(false)
if err != nil {
var vErr *ValidationError
if errors.As(err, &vErr) && vErr.code == ErrIDNotFound {
continue
}
return err
}
case *Array:
if isTopLevel && key == "_id" {
return newValidationError(ErrWrongIDType, fmt.Errorf("The '_id' value cannot be of type array"))
}
for i := 0; i < value.Len(); i++ {
item := must.NotFail(value.Get(i))
switch item := item.(type) {
case *Document:
err := item.validateData(false)
if err != nil {
var vErr *ValidationError
if errors.As(err, &vErr) && vErr.code == ErrIDNotFound {
continue
}
return err
}
case *Array:
return newValidationError(ErrValidation, fmt.Errorf(
"invalid value: { %q: %v } (nested arrays are not supported)", key, FormatAnyValue(value),
))
case float64:
if item == 0 && math.Signbit(item) {
must.NoError(value.Set(i, math.Copysign(0, +1)))
}
}
}
case float64:
if math.IsInf(value, 0) {
return newValidationError(
ErrValidation, fmt.Errorf("invalid value: { %q: %f } (infinity values are not allowed)", key, value),
)
}
if value == 0 && math.Signbit(value) {
d.Set(key, math.Copysign(0, +1))
}
case Regex:
if isTopLevel && key == "_id" {
return newValidationError(ErrWrongIDType, fmt.Errorf("The '_id' value cannot be of type regex"))
}
}
}
if !idPresent {
return newValidationError(ErrIDNotFound, fmt.Errorf("invalid document: document must contain '_id' field"))
}
return nil
}