| 1 | // Copyright 2020 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package interpreter |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "strings" |
| 20 | |
| 21 | "github.com/google/cel-go/common/containers" |
| 22 | "github.com/google/cel-go/common/types" |
| 23 | "github.com/google/cel-go/common/types/ref" |
| 24 | ) |
| 25 | |
| 26 | // AttributePattern represents a top-level variable with an optional set of qualifier patterns. |
| 27 | // |
| 28 | // When using a CEL expression within a container, e.g. a package or namespace, the variable name |
| 29 | // in the pattern must match the qualified name produced during the variable namespace resolution. |
| 30 | // For example, if variable `c` appears in an expression whose container is `a.b`, the variable |
| 31 | // name supplied to the pattern must be `a.b.c` |
| 32 | // |
| 33 | // The qualifier patterns for attribute matching must be one of the following: |
| 34 | // |
| 35 | // - valid map key type: string, int, uint, bool |
| 36 | // - wildcard (*) |
| 37 | // |
| 38 | // Examples: |
| 39 | // |
| 40 | // 1. ns.myvar["complex-value"] |
| 41 | // 2. ns.myvar["complex-value"][0] |
| 42 | // 3. ns.myvar["complex-value"].*.name |
| 43 | // |
| 44 | // The first example is simple: match an attribute where the variable is 'ns.myvar' with a |
| 45 | // field access on 'complex-value'. The second example expands the match to indicate that only |
| 46 | // a specific index `0` should match. And lastly, the third example matches any indexed access |
| 47 | // that later selects the 'name' field. |
| 48 | type AttributePattern struct { |
| 49 | variable string |
| 50 | qualifierPatterns []*AttributeQualifierPattern |
| 51 | } |
| 52 | |
| 53 | // NewAttributePattern produces a new mutable AttributePattern based on a variable name. |
| 54 | func NewAttributePattern(variable string) *AttributePattern { |
| 55 | return &AttributePattern{ |
| 56 | variable: variable, |
| 57 | qualifierPatterns: []*AttributeQualifierPattern{}, |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // QualString adds a string qualifier pattern to the AttributePattern. The string may be a valid |
| 62 | // identifier, or string map key including empty string. |
| 63 | func (apat *AttributePattern) QualString(pattern string) *AttributePattern { |
| 64 | apat.qualifierPatterns = append(apat.qualifierPatterns, |
| 65 | &AttributeQualifierPattern{value: pattern}) |
| 66 | return apat |
| 67 | } |
| 68 | |
| 69 | // QualInt adds an int qualifier pattern to the AttributePattern. The index may be either a map or |
| 70 | // list index. |
| 71 | func (apat *AttributePattern) QualInt(pattern int64) *AttributePattern { |
| 72 | apat.qualifierPatterns = append(apat.qualifierPatterns, |
| 73 | &AttributeQualifierPattern{value: pattern}) |
| 74 | return apat |
| 75 | } |
| 76 | |
| 77 | // QualUint adds an uint qualifier pattern for a map index operation to the AttributePattern. |
| 78 | func (apat *AttributePattern) QualUint(pattern uint64) *AttributePattern { |
| 79 | apat.qualifierPatterns = append(apat.qualifierPatterns, |
| 80 | &AttributeQualifierPattern{value: pattern}) |
| 81 | return apat |
| 82 | } |
| 83 | |
| 84 | // QualBool adds a bool qualifier pattern for a map index operation to the AttributePattern. |
| 85 | func (apat *AttributePattern) QualBool(pattern bool) *AttributePattern { |
| 86 | apat.qualifierPatterns = append(apat.qualifierPatterns, |
| 87 | &AttributeQualifierPattern{value: pattern}) |
| 88 | return apat |
| 89 | } |
| 90 | |
| 91 | // Wildcard adds a special sentinel qualifier pattern that will match any single qualifier. |
| 92 | func (apat *AttributePattern) Wildcard() *AttributePattern { |
| 93 | apat.qualifierPatterns = append(apat.qualifierPatterns, |
| 94 | &AttributeQualifierPattern{wildcard: true}) |
| 95 | return apat |
| 96 | } |
| 97 | |
| 98 | // VariableMatches returns true if the fully qualified variable matches the AttributePattern |
| 99 | // fully qualified variable name. |
| 100 | func (apat *AttributePattern) VariableMatches(variable string) bool { |
| 101 | return apat.variable == variable |
| 102 | } |
| 103 | |
| 104 | // QualifierPatterns returns the set of AttributeQualifierPattern values on the AttributePattern. |
| 105 | func (apat *AttributePattern) QualifierPatterns() []*AttributeQualifierPattern { |
| 106 | return apat.qualifierPatterns |
| 107 | } |
| 108 | |
| 109 | // AttributeQualifierPattern holds a wildcard or valued qualifier pattern. |
| 110 | type AttributeQualifierPattern struct { |
| 111 | wildcard bool |
| 112 | value any |
| 113 | } |
| 114 | |
| 115 | // Matches returns true if the qualifier pattern is a wildcard, or the Qualifier implements the |
| 116 | // qualifierValueEquator interface and its IsValueEqualTo returns true for the qualifier pattern. |
| 117 | func (qpat *AttributeQualifierPattern) Matches(q Qualifier) bool { |
| 118 | if qpat.wildcard { |
| 119 | return true |
| 120 | } |
| 121 | qve, ok := q.(qualifierValueEquator) |
| 122 | return ok && qve.QualifierValueEquals(qpat.value) |
| 123 | } |
| 124 | |
| 125 | // qualifierValueEquator defines an interface for determining if an input value, of valid map key |
| 126 | // type, is equal to the value held in the Qualifier. This interface is used by the |
| 127 | // AttributeQualifierPattern to determine pattern matches for non-wildcard qualifier patterns. |
| 128 | // |
| 129 | // Note: Attribute values are also Qualifier values; however, Attributes are resolved before |
| 130 | // qualification happens. This is an implementation detail, but one relevant to why the Attribute |
| 131 | // types do not surface in the list of implementations. |
| 132 | // |
| 133 | // See: partialAttributeFactory.matchesUnknownPatterns for more details on how this interface is |
| 134 | // used. |
| 135 | type qualifierValueEquator interface { |
| 136 | // QualifierValueEquals returns true if the input value is equal to the value held in the |
| 137 | // Qualifier. |
| 138 | QualifierValueEquals(value any) bool |
| 139 | } |
| 140 | |
| 141 | // QualifierValueEquals implementation for boolean qualifiers. |
| 142 | func (q *boolQualifier) QualifierValueEquals(value any) bool { |
| 143 | bval, ok := value.(bool) |
| 144 | return ok && q.value == bval |
| 145 | } |
| 146 | |
| 147 | // QualifierValueEquals implementation for field qualifiers. |
| 148 | func (q *fieldQualifier) QualifierValueEquals(value any) bool { |
| 149 | sval, ok := value.(string) |
| 150 | return ok && q.Name == sval |
| 151 | } |
| 152 | |
| 153 | // QualifierValueEquals implementation for string qualifiers. |
| 154 | func (q *stringQualifier) QualifierValueEquals(value any) bool { |
| 155 | sval, ok := value.(string) |
| 156 | return ok && q.value == sval |
| 157 | } |
| 158 | |
| 159 | // QualifierValueEquals implementation for int qualifiers. |
| 160 | func (q *intQualifier) QualifierValueEquals(value any) bool { |
| 161 | return numericValueEquals(value, q.celValue) |
| 162 | } |
| 163 | |
| 164 | // QualifierValueEquals implementation for uint qualifiers. |
| 165 | func (q *uintQualifier) QualifierValueEquals(value any) bool { |
| 166 | return numericValueEquals(value, q.celValue) |
| 167 | } |
| 168 | |
| 169 | // QualifierValueEquals implementation for double qualifiers. |
| 170 | func (q *doubleQualifier) QualifierValueEquals(value any) bool { |
| 171 | return numericValueEquals(value, q.celValue) |
| 172 | } |
| 173 | |
| 174 | // numericValueEquals uses CEL equality to determine whether two number values are |
| 175 | func numericValueEquals(value any, celValue ref.Val) bool { |
| 176 | val := types.DefaultTypeAdapter.NativeToValue(value) |
| 177 | return celValue.Equal(val) == types.True |
| 178 | } |
| 179 | |
| 180 | // NewPartialAttributeFactory returns an AttributeFactory implementation capable of performing |
| 181 | // AttributePattern matches with PartialActivation inputs. |
| 182 | func NewPartialAttributeFactory(container *containers.Container, adapter types.Adapter, provider types.Provider, opts ...AttrFactoryOption) AttributeFactory { |
| 183 | fac := NewAttributeFactory(container, adapter, provider, opts...) |
| 184 | return &partialAttributeFactory{ |
| 185 | AttributeFactory: fac, |
| 186 | container: container, |
| 187 | adapter: adapter, |
| 188 | provider: provider, |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | type partialAttributeFactory struct { |
| 193 | AttributeFactory |
| 194 | container *containers.Container |
| 195 | adapter types.Adapter |
| 196 | provider types.Provider |
| 197 | } |
| 198 | |
| 199 | // AbsoluteAttribute implementation of the AttributeFactory interface which wraps the |
| 200 | // NamespacedAttribute resolution in an internal attributeMatcher object to dynamically match |
| 201 | // unknown patterns from PartialActivation inputs if given. |
| 202 | func (fac *partialAttributeFactory) AbsoluteAttribute(id int64, names ...string) NamespacedAttribute { |
| 203 | attr := fac.AttributeFactory.AbsoluteAttribute(id, names...) |
| 204 | return &attributeMatcher{fac: fac, NamespacedAttribute: attr} |
| 205 | } |
| 206 | |
| 207 | // MaybeAttribute implementation of the AttributeFactory interface which ensure that the set of |
| 208 | // 'maybe' NamespacedAttribute values are produced using the partialAttributeFactory rather than |
| 209 | // the base AttributeFactory implementation. |
| 210 | func (fac *partialAttributeFactory) MaybeAttribute(id int64, name string) Attribute { |
| 211 | var names []string |
| 212 | // When there's a single name with a dot prefix, it indicates that the 'maybe' attribute is a |
| 213 | // globally namespaced identifier. |
| 214 | if strings.HasPrefix(name, ".") { |
| 215 | names = append(names, name) |
| 216 | } else { |
| 217 | // In all other cases, the candidate names should be inferred. |
| 218 | names = fac.container.ResolveCandidateNames(name) |
| 219 | } |
| 220 | return &maybeAttribute{ |
| 221 | id: id, |
| 222 | attrs: []NamespacedAttribute{ |
| 223 | fac.AbsoluteAttribute(id, names...), |
| 224 | }, |
| 225 | adapter: fac.adapter, |
| 226 | provider: fac.provider, |
| 227 | fac: fac, |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // matchesUnknownPatterns returns true if the variable names and qualifiers for a given |
| 232 | // Attribute value match any of the ActivationPattern objects in the set of unknown activation |
| 233 | // patterns on the given PartialActivation. |
| 234 | // |
| 235 | // For example, in the expression `a.b`, the Attribute is composed of variable `a`, with string |
| 236 | // qualifier `b`. When a PartialActivation is supplied, it indicates that some or all of the data |
| 237 | // provided in the input is unknown by specifying unknown AttributePatterns. An AttributePattern |
| 238 | // that refers to variable `a` with a string qualifier of `c` will not match `a.b`; however, any |
| 239 | // of the following patterns will match Attribute `a.b`: |
| 240 | // |
| 241 | // - `AttributePattern("a")` |
| 242 | // - `AttributePattern("a").Wildcard()` |
| 243 | // - `AttributePattern("a").QualString("b")` |
| 244 | // - `AttributePattern("a").QualString("b").QualInt(0)` |
| 245 | // |
| 246 | // Any AttributePattern which overlaps an Attribute or vice-versa will produce an Unknown result |
| 247 | // for the last pattern matched variable or qualifier in the Attribute. In the first matching |
| 248 | // example, the expression id representing variable `a` would be listed in the Unknown result, |
| 249 | // whereas in the other pattern examples, the qualifier `b` would be returned as the Unknown. |
| 250 | func (fac *partialAttributeFactory) matchesUnknownPatterns( |
| 251 | vars PartialActivation, |
| 252 | attrID int64, |
| 253 | variableNames []string, |
| 254 | qualifiers []Qualifier) (*types.Unknown, error) { |
| 255 | patterns := vars.UnknownAttributePatterns() |
| 256 | candidateIndices := map[int]struct{}{} |
| 257 | for _, variable := range variableNames { |
| 258 | for i, pat := range patterns { |
| 259 | if pat.VariableMatches(variable) { |
| 260 | if len(qualifiers) == 0 { |
| 261 | return types.NewUnknown(attrID, types.NewAttributeTrail(variable)), nil |
| 262 | } |
| 263 | candidateIndices[i] = struct{}{} |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | // Determine whether to return early if there are no candidate unknown patterns. |
| 268 | if len(candidateIndices) == 0 { |
| 269 | return nil, nil |
| 270 | } |
| 271 | // Resolve the attribute qualifiers into a static set. This prevents more dynamic |
| 272 | // Attribute resolutions than necessary when there are multiple unknown patterns |
| 273 | // that traverse the same Attribute-based qualifier field. |
| 274 | newQuals := make([]Qualifier, len(qualifiers)) |
| 275 | for i, qual := range qualifiers { |
| 276 | attr, isAttr := qual.(Attribute) |
| 277 | if isAttr { |
| 278 | val, err := attr.Resolve(vars) |
| 279 | if err != nil { |
| 280 | return nil, err |
| 281 | } |
| 282 | // If this resolution behavior ever changes, new implementations of the |
| 283 | // qualifierValueEquator may be required to handle proper resolution. |
| 284 | qual, err = fac.NewQualifier(nil, qual.ID(), val, attr.IsOptional()) |
| 285 | if err != nil { |
| 286 | return nil, err |
| 287 | } |
| 288 | } |
| 289 | newQuals[i] = qual |
| 290 | } |
| 291 | // Determine whether any of the unknown patterns match. |
| 292 | for patIdx := range candidateIndices { |
| 293 | pat := patterns[patIdx] |
| 294 | isUnk := true |
| 295 | matchExprID := attrID |
| 296 | qualPats := pat.QualifierPatterns() |
| 297 | for i, qual := range newQuals { |
| 298 | if i >= len(qualPats) { |
| 299 | break |
| 300 | } |
| 301 | matchExprID = qual.ID() |
| 302 | qualPat := qualPats[i] |
| 303 | // Note, the AttributeQualifierPattern relies on the input Qualifier not being an |
| 304 | // Attribute, since there is no way to resolve the Attribute with the information |
| 305 | // provided to the Matches call. |
| 306 | if !qualPat.Matches(qual) { |
| 307 | isUnk = false |
| 308 | break |
| 309 | } |
| 310 | } |
| 311 | if isUnk { |
| 312 | attr := types.NewAttributeTrail(pat.variable) |
| 313 | for i := 0; i < len(qualPats) && i < len(newQuals); i++ { |
| 314 | if qual, ok := newQuals[i].(ConstantQualifier); ok { |
| 315 | switch v := qual.Value().Value().(type) { |
| 316 | case bool: |
| 317 | types.QualifyAttribute[bool](attr, v) |
| 318 | case float64: |
| 319 | types.QualifyAttribute[int64](attr, int64(v)) |
| 320 | case int64: |
| 321 | types.QualifyAttribute[int64](attr, v) |
| 322 | case string: |
| 323 | types.QualifyAttribute[string](attr, v) |
| 324 | case uint64: |
| 325 | types.QualifyAttribute[uint64](attr, v) |
| 326 | default: |
| 327 | types.QualifyAttribute[string](attr, fmt.Sprintf("%v", v)) |
| 328 | } |
| 329 | } else { |
| 330 | types.QualifyAttribute[string](attr, "*") |
| 331 | } |
| 332 | } |
| 333 | return types.NewUnknown(matchExprID, attr), nil |
| 334 | } |
| 335 | } |
| 336 | return nil, nil |
| 337 | } |
| 338 | |
| 339 | // attributeMatcher embeds the NamespacedAttribute interface which allows it to participate in |
| 340 | // AttributePattern matching against Attribute values without having to modify the code paths that |
| 341 | // identify Attributes in expressions. |
| 342 | type attributeMatcher struct { |
| 343 | NamespacedAttribute |
| 344 | qualifiers []Qualifier |
| 345 | fac *partialAttributeFactory |
| 346 | } |
| 347 | |
| 348 | // AddQualifier implements the Attribute interface method. |
| 349 | func (m *attributeMatcher) AddQualifier(qual Qualifier) (Attribute, error) { |
| 350 | // Add the qualifier to the embedded NamespacedAttribute. If the input to the Resolve |
| 351 | // method is not a PartialActivation, or does not match an unknown attribute pattern, the |
| 352 | // Resolve method is directly invoked on the underlying NamespacedAttribute. |
| 353 | _, err := m.NamespacedAttribute.AddQualifier(qual) |
| 354 | if err != nil { |
| 355 | return nil, err |
| 356 | } |
| 357 | // The attributeMatcher overloads TryResolve and will attempt to match unknown patterns against |
| 358 | // the variable name and qualifier set contained within the Attribute. These values are not |
| 359 | // directly inspectable on the top-level NamespacedAttribute interface and so are tracked within |
| 360 | // the attributeMatcher. |
| 361 | m.qualifiers = append(m.qualifiers, qual) |
| 362 | return m, nil |
| 363 | } |
| 364 | |
| 365 | // Resolve is an implementation of the NamespacedAttribute interface method which tests |
| 366 | // for matching unknown attribute patterns and returns types.Unknown if present. Otherwise, |
| 367 | // the standard Resolve logic applies. |
| 368 | func (m *attributeMatcher) Resolve(vars Activation) (any, error) { |
| 369 | id := m.NamespacedAttribute.ID() |
| 370 | // Bug in how partial activation is resolved, should search parents as well. |
| 371 | partial, isPartial := AsPartialActivation(vars) |
| 372 | if isPartial { |
| 373 | unk, err := m.fac.matchesUnknownPatterns( |
| 374 | partial, |
| 375 | id, |
| 376 | m.CandidateVariableNames(), |
| 377 | m.qualifiers) |
| 378 | if err != nil { |
| 379 | return nil, err |
| 380 | } |
| 381 | if unk != nil { |
| 382 | return unk, nil |
| 383 | } |
| 384 | } |
| 385 | return m.NamespacedAttribute.Resolve(vars) |
| 386 | } |
| 387 | |
| 388 | // Qualify is an implementation of the Qualifier interface method. |
| 389 | func (m *attributeMatcher) Qualify(vars Activation, obj any) (any, error) { |
| 390 | return attrQualify(m.fac, vars, obj, m) |
| 391 | } |
| 392 | |
| 393 | // QualifyIfPresent is an implementation of the Qualifier interface method. |
| 394 | func (m *attributeMatcher) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { |
| 395 | return attrQualifyIfPresent(m.fac, vars, obj, m, presenceOnly) |
| 396 | } |