17944: Adds a case-insensitive check for key/value against labels.
[arvados.git] / sdk / go / arvados / vocabulary.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "encoding/json"
10         "fmt"
11         "reflect"
12         "strings"
13 )
14
15 type Vocabulary struct {
16         reservedTagKeys map[string]bool          `json:"-"`
17         StrictTags      bool                     `json:"strict_tags"`
18         Tags            map[string]VocabularyTag `json:"tags"`
19 }
20
21 type VocabularyTag struct {
22         Strict bool                          `json:"strict"`
23         Labels []VocabularyLabel             `json:"labels"`
24         Values map[string]VocabularyTagValue `json:"values"`
25 }
26
27 // Cannot have a constant map in Go, so we have to use a function
28 func (v *Vocabulary) systemTagKeys() map[string]bool {
29         return map[string]bool{
30                 "type":                  true,
31                 "template_uuid":         true,
32                 "groups":                true,
33                 "username":              true,
34                 "image_timestamp":       true,
35                 "docker-image-repo-tag": true,
36                 "filters":               true,
37                 "container_request":     true,
38         }
39 }
40
41 type VocabularyLabel struct {
42         Label string `json:"label"`
43 }
44
45 type VocabularyTagValue struct {
46         Labels []VocabularyLabel `json:"labels"`
47 }
48
49 // NewVocabulary creates a new Vocabulary from a JSON definition and a list
50 // of reserved tag keys that will get special treatment when strict mode is
51 // enabled.
52 func NewVocabulary(data []byte, managedTagKeys []string) (voc *Vocabulary, err error) {
53         if r := bytes.Compare(data, []byte("")); r == 0 {
54                 return &Vocabulary{}, nil
55         }
56         err = json.Unmarshal(data, &voc)
57         if err != nil {
58                 return nil, fmt.Errorf("invalid JSON format error: %q", err)
59         }
60         if reflect.DeepEqual(voc, &Vocabulary{}) {
61                 return nil, fmt.Errorf("JSON data provided doesn't match Vocabulary format: %q", data)
62         }
63         voc.reservedTagKeys = make(map[string]bool)
64         for _, managedKey := range managedTagKeys {
65                 voc.reservedTagKeys[managedKey] = true
66         }
67         for systemKey := range voc.systemTagKeys() {
68                 voc.reservedTagKeys[systemKey] = true
69         }
70         err = voc.validate()
71         if err != nil {
72                 return nil, err
73         }
74         return voc, nil
75 }
76
77 func (v *Vocabulary) validate() error {
78         if v == nil {
79                 return nil
80         }
81         tagKeys := map[string]string{}
82         // Checks for Vocabulary strictness
83         if v.StrictTags && len(v.Tags) == 0 {
84                 return fmt.Errorf("vocabulary is strict but no tags are defined")
85         }
86         // Checks for collisions between tag keys, reserved tag keys
87         // and tag key labels.
88         for key := range v.Tags {
89                 if v.reservedTagKeys[key] {
90                         return fmt.Errorf("tag key %q is reserved", key)
91                 }
92                 lcKey := strings.ToLower(key)
93                 if tagKeys[lcKey] != "" {
94                         return fmt.Errorf("duplicate tag key %q", key)
95                 }
96                 tagKeys[lcKey] = key
97                 for _, lbl := range v.Tags[key].Labels {
98                         label := strings.ToLower(lbl.Label)
99                         if tagKeys[label] != "" {
100                                 return fmt.Errorf("tag label %q for key %q already seen as a tag key or label", lbl.Label, key)
101                         }
102                         tagKeys[label] = lbl.Label
103                 }
104                 // Checks for value strictness
105                 if v.Tags[key].Strict && len(v.Tags[key].Values) == 0 {
106                         return fmt.Errorf("tag key %q is configured as strict but doesn't provide values", key)
107                 }
108                 // Checks for collisions between tag values and tag value labels.
109                 tagValues := map[string]string{}
110                 for val := range v.Tags[key].Values {
111                         lcVal := strings.ToLower(val)
112                         if tagValues[lcVal] != "" {
113                                 return fmt.Errorf("duplicate tag value %q for tag %q", val, key)
114                         }
115                         tagValues[lcVal] = val
116                         for _, tagLbl := range v.Tags[key].Values[val].Labels {
117                                 label := strings.ToLower(tagLbl.Label)
118                                 if tagValues[label] != "" {
119                                         return fmt.Errorf("tag value label %q for pair (%q:%q) already seen as a value key or label", tagLbl.Label, key, val)
120                                 }
121                                 tagValues[label] = tagLbl.Label
122                         }
123                 }
124         }
125         return nil
126 }
127
128 func (v *Vocabulary) getLabelsToKeys() (labels map[string]string) {
129         if v == nil {
130                 return
131         }
132         labels = make(map[string]string)
133         for key, val := range v.Tags {
134                 for _, lbl := range val.Labels {
135                         label := strings.ToLower(lbl.Label)
136                         labels[label] = key
137                 }
138         }
139         return labels
140 }
141
142 func (v *Vocabulary) getLabelsToValues(key string) (labels map[string]string) {
143         if v == nil {
144                 return
145         }
146         labels = make(map[string]string)
147         if _, ok := v.Tags[key]; ok {
148                 for val := range v.Tags[key].Values {
149                         labels[strings.ToLower(val)] = val
150                         for _, tagLbl := range v.Tags[key].Values[val].Labels {
151                                 label := strings.ToLower(tagLbl.Label)
152                                 labels[label] = val
153                         }
154                 }
155         }
156         return labels
157 }
158
159 func (v *Vocabulary) checkValue(key, val string) error {
160         if _, ok := v.Tags[key].Values[val]; !ok {
161                 lcVal := strings.ToLower(val)
162                 correctValue, ok := v.getLabelsToValues(key)[lcVal]
163                 if ok {
164                         return fmt.Errorf("tag value %q for key %q is an alias, must be provided as %q", val, key, correctValue)
165                 } else if v.Tags[key].Strict {
166                         return fmt.Errorf("tag value %q is not valid for key %q", val, key)
167                 }
168         }
169         return nil
170 }
171
172 // Check validates the given data against the vocabulary.
173 func (v *Vocabulary) Check(data map[string]interface{}) error {
174         if v == nil {
175                 return nil
176         }
177         for key, val := range data {
178                 // Checks for key validity
179                 if v.reservedTagKeys[key] {
180                         // Allow reserved keys to be used even if they are not defined in
181                         // the vocabulary no matter its strictness.
182                         continue
183                 }
184                 if _, ok := v.Tags[key]; !ok {
185                         lcKey := strings.ToLower(key)
186                         correctKey, ok := v.getLabelsToKeys()[lcKey]
187                         if ok {
188                                 return fmt.Errorf("tag key %q is an alias, must be provided as %q", key, correctKey)
189                         } else if v.StrictTags {
190                                 return fmt.Errorf("tag key %q is not defined in the vocabulary", key)
191                         }
192                         // If the key is not defined, we don't need to check the value
193                         continue
194                 }
195                 // Checks for value validity -- key is defined
196                 switch val := val.(type) {
197                 case string:
198                         err := v.checkValue(key, val)
199                         if err != nil {
200                                 return err
201                         }
202                 case []interface{}:
203                         for _, singleVal := range val {
204                                 switch singleVal := singleVal.(type) {
205                                 case string:
206                                         err := v.checkValue(key, singleVal)
207                                         if err != nil {
208                                                 return err
209                                         }
210                                 default:
211                                         return fmt.Errorf("tag value of type %T for key %q is not a valid", singleVal, key)
212                                 }
213                         }
214                 default:
215                         return fmt.Errorf("tag value of type %T for key %q is not a valid", val, key)
216                 }
217         }
218         return nil
219 }