Coverage Report

Created: 2026-11-12 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/extensions/protobuf/internal/qualify.cc
Line
Count
Source
1
// Copyright 2024 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
//     https://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
#include "extensions/protobuf/internal/qualify.h"
16
17
#include <cstdint>
18
#include <string>
19
#include <utility>
20
21
#include "absl/functional/overload.h"
22
#include "absl/log/absl_check.h"
23
#include "absl/status/status.h"
24
#include "absl/status/statusor.h"
25
#include "absl/strings/str_cat.h"
26
#include "absl/types/optional.h"
27
#include "absl/types/variant.h"
28
#include "base/attribute.h"
29
#include "base/builtins.h"
30
#include "common/kind.h"
31
#include "common/memory.h"
32
#include "extensions/protobuf/internal/map_reflection.h"
33
#include "internal/status_macros.h"
34
#include "runtime/internal/errors.h"
35
#include "runtime/runtime_options.h"
36
#include "google/protobuf/descriptor.h"
37
#include "google/protobuf/map_field.h"
38
#include "google/protobuf/message.h"
39
#include "google/protobuf/reflection.h"
40
41
#undef GetMessage
42
43
namespace cel::extensions::protobuf_internal {
44
45
namespace {
46
47
const google::protobuf::FieldDescriptor* GetNormalizedFieldByNumber(
48
    const google::protobuf::Descriptor* descriptor, const google::protobuf::Reflection* reflection,
49
0
    int field_number) {
50
0
  const google::protobuf::FieldDescriptor* field_desc =
51
0
      descriptor->FindFieldByNumber(field_number);
52
0
  if (field_desc == nullptr && reflection != nullptr) {
53
0
    field_desc = reflection->FindKnownExtensionByNumber(field_number);
54
0
  }
55
0
  return field_desc;
56
0
}
57
58
// JSON container types and Any have special unpacking rules.
59
//
60
// Not considered for qualify traversal for simplicity, but
61
// could be supported in a follow-up if needed.
62
0
bool IsUnsupportedQualifyType(const google::protobuf::Descriptor& desc) {
63
0
  switch (desc.well_known_type()) {
64
0
    case google::protobuf::Descriptor::WELLKNOWNTYPE_ANY:
65
0
    case google::protobuf::Descriptor::WELLKNOWNTYPE_STRUCT:
66
0
    case google::protobuf::Descriptor::WELLKNOWNTYPE_VALUE:
67
0
    case google::protobuf::Descriptor::WELLKNOWNTYPE_LISTVALUE:
68
0
      return true;
69
0
    default:
70
0
      return false;
71
0
  }
72
0
}
73
74
constexpr int kKeyTag = 1;
75
constexpr int kValueTag = 2;
76
77
bool MatchesMapKeyType(const google::protobuf::FieldDescriptor* key_desc,
78
0
                       const cel::AttributeQualifier& key) {
79
0
  switch (key_desc->cpp_type()) {
80
0
    case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
81
0
      return key.kind() == cel::Kind::kBool;
82
0
    case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
83
      // fall through
84
0
    case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
85
0
      return key.kind() == cel::Kind::kInt64;
86
0
    case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
87
      // fall through
88
0
    case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
89
0
      return key.kind() == cel::Kind::kUint64;
90
0
    case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
91
0
      return key.kind() == cel::Kind::kString;
92
93
0
    default:
94
0
      return false;
95
0
  }
96
0
}
97
98
absl::StatusOr<absl::optional<google::protobuf::MapValueConstRef>> LookupMapValue(
99
    const google::protobuf::Message* message, const google::protobuf::Reflection* reflection,
100
    const google::protobuf::FieldDescriptor* field_desc,
101
    const google::protobuf::FieldDescriptor* key_desc,
102
0
    const cel::AttributeQualifier& key) {
103
0
  if (!MatchesMapKeyType(key_desc, key)) {
104
0
    return runtime_internal::CreateInvalidMapKeyTypeError(
105
0
        key_desc->cpp_type_name());
106
0
  }
107
108
0
  google::protobuf::MapKey proto_key;
109
0
  switch (key_desc->cpp_type()) {
110
0
    case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
111
0
      proto_key.SetBoolValue(*key.GetBoolKey());
112
0
      break;
113
0
    case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
114
0
      int64_t key_value = *key.GetInt64Key();
115
0
      if (key_value > std::numeric_limits<int32_t>::max() ||
116
0
          key_value < std::numeric_limits<int32_t>::lowest()) {
117
0
        return absl::OutOfRangeError("integer overflow");
118
0
      }
119
0
      proto_key.SetInt32Value(key_value);
120
0
    } break;
121
0
    case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
122
0
      proto_key.SetInt64Value(*key.GetInt64Key());
123
0
      break;
124
0
    case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
125
0
      proto_key.SetStringValue(*key.GetStringKey());
126
0
    } break;
127
0
    case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
128
0
      uint64_t key_value = *key.GetUint64Key();
129
0
      if (key_value > std::numeric_limits<uint32_t>::max()) {
130
0
        return absl::OutOfRangeError("unsigned integer overflow");
131
0
      }
132
0
      proto_key.SetUInt32Value(key_value);
133
0
    } break;
134
0
    case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
135
0
      proto_key.SetUInt64Value(*key.GetUint64Key());
136
0
    } break;
137
0
    default:
138
0
      return runtime_internal::CreateInvalidMapKeyTypeError(
139
0
          key_desc->cpp_type_name());
140
0
  }
141
142
  // Look the value up
143
0
  google::protobuf::MapValueConstRef value_ref;
144
0
  bool found = cel::extensions::protobuf_internal::LookupMapValue(
145
0
      *reflection, *message, *field_desc, proto_key, &value_ref);
146
0
  if (!found) {
147
0
    return std::nullopt;
148
0
  }
149
0
  return value_ref;
150
0
}
151
152
bool FieldIsPresent(const google::protobuf::Message* message,
153
                    const google::protobuf::FieldDescriptor* field_desc,
154
0
                    const google::protobuf::Reflection* reflection) {
155
0
  if (field_desc->is_map()) {
156
    // When the map field appears in a has(msg.map_field) expression, the map
157
    // is considered 'present' when it is non-empty. Since maps are repeated
158
    // fields they don't participate with standard proto presence testing
159
    // since the repeated field is always at least empty.
160
0
    return reflection->FieldSize(*message, field_desc) != 0;
161
0
  }
162
163
0
  if (field_desc->is_repeated()) {
164
    // When the list field appears in a has(msg.list_field) expression, the
165
    // list is considered 'present' when it is non-empty.
166
0
    return reflection->FieldSize(*message, field_desc) != 0;
167
0
  }
168
169
  // Standard proto presence test for non-repeated fields.
170
0
  return reflection->HasField(*message, field_desc);
171
0
}
172
173
}  // namespace
174
175
absl::Status ProtoQualifyState::ApplySelectQualifier(
176
0
    const cel::SelectQualifier& qualifier, MemoryManagerRef memory_manager) {
177
0
  return absl::visit(
178
0
      absl::Overload(
179
0
          [&](const cel::AttributeQualifier& qualifier) -> absl::Status {
180
0
            if (repeated_field_desc_ == nullptr) {
181
0
              return absl::UnimplementedError(
182
0
                  "dynamic field access on message not supported");
183
0
            }
184
0
            return ApplyAttributeQualifer(qualifier, memory_manager);
185
0
          },
186
0
          [&](const cel::FieldSpecifier& field_specifier) -> absl::Status {
187
0
            if (repeated_field_desc_ != nullptr) {
188
0
              return absl::UnimplementedError(
189
0
                  "strong field access on container not supported");
190
0
            }
191
0
            return ApplyFieldSpecifier(field_specifier, memory_manager);
192
0
          }),
193
0
      qualifier);
194
0
}
195
196
absl::Status ProtoQualifyState::ApplyLastQualifierHas(
197
0
    const cel::SelectQualifier& qualifier, MemoryManagerRef memory_manager) {
198
0
  const cel::FieldSpecifier* specifier =
199
0
      absl::get_if<cel::FieldSpecifier>(&qualifier);
200
0
  return absl::visit(
201
0
      absl::Overload(
202
0
          [&](const cel::AttributeQualifier& qualifier) mutable
203
0
          -> absl::Status {
204
0
            if (qualifier.kind() != cel::Kind::kString ||
205
0
                repeated_field_desc_ == nullptr ||
206
0
                !repeated_field_desc_->is_map()) {
207
0
              SetResultFromError(
208
0
                  runtime_internal::CreateNoMatchingOverloadError("has"),
209
0
                  memory_manager);
210
0
              return absl::OkStatus();
211
0
            }
212
0
            return MapHas(qualifier, memory_manager);
213
0
          },
214
0
          [&](const cel::FieldSpecifier& field_specifier) mutable
215
0
          -> absl::Status {
216
0
            const auto* field_desc = GetNormalizedFieldByNumber(
217
0
                descriptor_, reflection_, specifier->number);
218
0
            if (field_desc == nullptr) {
219
0
              SetResultFromError(
220
0
                  runtime_internal::CreateNoSuchFieldError(specifier->name),
221
0
                  memory_manager);
222
0
              return absl::OkStatus();
223
0
            }
224
0
            SetResultFromBool(
225
0
                FieldIsPresent(message_, field_desc, reflection_));
226
0
            return absl::OkStatus();
227
0
          }),
228
0
      qualifier);
229
0
}
230
231
absl::Status ProtoQualifyState::ApplyLastQualifierGet(
232
0
    const cel::SelectQualifier& qualifier, MemoryManagerRef memory_manager) {
233
0
  return absl::visit(
234
0
      absl::Overload(
235
0
          [&](const cel::AttributeQualifier& attr_qualifier) mutable
236
0
          -> absl::Status {
237
0
            if (repeated_field_desc_ == nullptr) {
238
0
              return absl::UnimplementedError(
239
0
                  "dynamic field access on message not supported");
240
0
            }
241
0
            if (repeated_field_desc_->is_map()) {
242
0
              return ApplyLastQualifierGetMap(attr_qualifier, memory_manager);
243
0
            }
244
0
            return ApplyLastQualifierGetList(attr_qualifier, memory_manager);
245
0
          },
246
0
          [&](const cel::FieldSpecifier& specifier) mutable -> absl::Status {
247
0
            if (repeated_field_desc_ != nullptr) {
248
0
              return absl::UnimplementedError(
249
0
                  "strong field access on container not supported");
250
0
            }
251
0
            return ApplyLastQualifierMessageGet(specifier, memory_manager);
252
0
          }),
253
0
      qualifier);
254
0
}
255
256
absl::Status ProtoQualifyState::ApplyFieldSpecifier(
257
    const cel::FieldSpecifier& field_specifier,
258
0
    MemoryManagerRef memory_manager) {
259
0
  const google::protobuf::FieldDescriptor* field_desc = GetNormalizedFieldByNumber(
260
0
      descriptor_, reflection_, field_specifier.number);
261
0
  if (field_desc == nullptr) {
262
0
    SetResultFromError(
263
0
        runtime_internal::CreateNoSuchFieldError(field_specifier.name),
264
0
        memory_manager);
265
0
    return absl::OkStatus();
266
0
  }
267
268
0
  if (field_desc->is_repeated()) {
269
0
    repeated_field_desc_ = field_desc;
270
0
    return absl::OkStatus();
271
0
  }
272
273
0
  if (field_desc->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE ||
274
0
      IsUnsupportedQualifyType(*field_desc->message_type())) {
275
0
    CEL_RETURN_IF_ERROR(SetResultFromField(message_, field_desc,
276
0
                                           ProtoWrapperTypeOptions::kUnsetNull,
277
0
                                           memory_manager));
278
0
    return absl::OkStatus();
279
0
  }
280
281
0
  message_ = &reflection_->GetMessage(*message_, field_desc);
282
0
  descriptor_ = message_->GetDescriptor();
283
0
  reflection_ = message_->GetReflection();
284
0
  return absl::OkStatus();
285
0
}
286
287
absl::StatusOr<int> ProtoQualifyState::CheckListIndex(
288
0
    const cel::AttributeQualifier& qualifier) const {
289
0
  if (qualifier.kind() != cel::Kind::kInt64) {
290
0
    return runtime_internal::CreateNoMatchingOverloadError(
291
0
        cel::builtin::kIndex);
292
0
  }
293
294
0
  int64_t index = *qualifier.AsInt();
295
0
  int size = reflection_->FieldSize(*message_, repeated_field_desc_);
296
0
  if (index < 0 || index >= size) {
297
0
    return absl::InvalidArgumentError(
298
0
        absl::StrCat("index out of bounds: index=", index, " size=", size));
299
0
  }
300
0
  return static_cast<int>(index);
301
0
}
302
303
absl::Status ProtoQualifyState::ApplyAttributeQualifierList(
304
0
    const cel::AttributeQualifier& qualifier, MemoryManagerRef memory_manager) {
305
0
  ABSL_DCHECK_NE(repeated_field_desc_, nullptr);
306
0
  ABSL_DCHECK(!repeated_field_desc_->is_map());
307
0
  ABSL_DCHECK_EQ(repeated_field_desc_->cpp_type(),
308
0
                 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE);
309
310
0
  auto index_or = CheckListIndex(qualifier);
311
0
  if (!index_or.ok()) {
312
0
    SetResultFromError(std::move(index_or).status(), memory_manager);
313
0
    return absl::OkStatus();
314
0
  }
315
316
0
  if (IsUnsupportedQualifyType(*repeated_field_desc_->message_type())) {
317
0
    CEL_RETURN_IF_ERROR(SetResultFromRepeatedField(
318
0
        message_, repeated_field_desc_, *index_or, memory_manager));
319
0
    return absl::OkStatus();
320
0
  }
321
322
0
  message_ = &reflection_->GetRepeatedMessage(*message_, repeated_field_desc_,
323
0
                                              *index_or);
324
0
  descriptor_ = message_->GetDescriptor();
325
0
  reflection_ = message_->GetReflection();
326
0
  repeated_field_desc_ = nullptr;
327
0
  return absl::OkStatus();
328
0
}
329
330
absl::StatusOr<google::protobuf::MapValueConstRef> ProtoQualifyState::CheckMapIndex(
331
0
    const cel::AttributeQualifier& qualifier) const {
332
0
  const auto* key_desc =
333
0
      repeated_field_desc_->message_type()->FindFieldByNumber(kKeyTag);
334
335
0
  CEL_ASSIGN_OR_RETURN(
336
0
      absl::optional<google::protobuf::MapValueConstRef> value_ref,
337
0
      LookupMapValue(message_, reflection_, repeated_field_desc_, key_desc,
338
0
                     qualifier));
339
340
0
  if (!value_ref.has_value()) {
341
0
    std::string key_string = qualifier.ToString();
342
0
    return runtime_internal::CreateNoSuchKeyError(key_string);
343
0
  }
344
0
  return std::move(value_ref).value();
345
0
}
346
347
absl::Status ProtoQualifyState::ApplyAttributeQualifierMap(
348
0
    const cel::AttributeQualifier& qualifier, MemoryManagerRef memory_manager) {
349
0
  ABSL_DCHECK_NE(repeated_field_desc_, nullptr);
350
0
  ABSL_DCHECK(repeated_field_desc_->is_map());
351
0
  ABSL_DCHECK_EQ(repeated_field_desc_->cpp_type(),
352
0
                 google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE);
353
354
0
  absl::StatusOr<google::protobuf::MapValueConstRef> value_ref = CheckMapIndex(qualifier);
355
0
  if (!value_ref.ok()) {
356
0
    SetResultFromError(std::move(value_ref).status(), memory_manager);
357
0
    return absl::OkStatus();
358
0
  }
359
360
0
  const auto* value_desc =
361
0
      repeated_field_desc_->message_type()->FindFieldByNumber(kValueTag);
362
363
0
  if (value_desc->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE ||
364
0
      IsUnsupportedQualifyType(*value_desc->message_type())) {
365
0
    CEL_RETURN_IF_ERROR(SetResultFromMapField(message_, value_desc, *value_ref,
366
0
                                              memory_manager));
367
0
    return absl::OkStatus();
368
0
  }
369
370
0
  message_ = &(value_ref->GetMessageValue());
371
0
  descriptor_ = message_->GetDescriptor();
372
0
  reflection_ = message_->GetReflection();
373
0
  repeated_field_desc_ = nullptr;
374
0
  return absl::OkStatus();
375
0
}
376
377
absl::Status ProtoQualifyState::ApplyAttributeQualifer(
378
0
    const cel::AttributeQualifier& qualifier, MemoryManagerRef memory_manager) {
379
0
  ABSL_DCHECK_NE(repeated_field_desc_, nullptr);
380
0
  if (repeated_field_desc_->cpp_type() !=
381
0
      google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
382
0
    return absl::InternalError("Unexpected qualify intermediate type");
383
0
  }
384
0
  if (repeated_field_desc_->is_map()) {
385
0
    return ApplyAttributeQualifierMap(qualifier, memory_manager);
386
0
  }  // else simple repeated
387
0
  return ApplyAttributeQualifierList(qualifier, memory_manager);
388
0
}
389
390
absl::Status ProtoQualifyState::MapHas(const cel::AttributeQualifier& key,
391
0
                                       MemoryManagerRef memory_manager) {
392
0
  const auto* key_desc =
393
0
      repeated_field_desc_->message_type()->FindFieldByNumber(kKeyTag);
394
395
0
  absl::StatusOr<absl::optional<google::protobuf::MapValueConstRef>> value_ref =
396
0
      LookupMapValue(message_, reflection_, repeated_field_desc_, key_desc,
397
0
                     key);
398
399
0
  if (!value_ref.ok()) {
400
0
    SetResultFromError(std::move(value_ref).status(), memory_manager);
401
0
    return absl::OkStatus();
402
0
  }
403
404
0
  SetResultFromBool(value_ref->has_value());
405
0
  return absl::OkStatus();
406
0
}
407
408
absl::Status ProtoQualifyState::ApplyLastQualifierMessageGet(
409
0
    const cel::FieldSpecifier& specifier, MemoryManagerRef memory_manager) {
410
0
  const auto* field_desc =
411
0
      GetNormalizedFieldByNumber(descriptor_, reflection_, specifier.number);
412
0
  if (field_desc == nullptr) {
413
0
    SetResultFromError(runtime_internal::CreateNoSuchFieldError(specifier.name),
414
0
                       memory_manager);
415
0
    return absl::OkStatus();
416
0
  }
417
0
  return SetResultFromField(message_, field_desc,
418
0
                            ProtoWrapperTypeOptions::kUnsetNull,
419
0
                            memory_manager);
420
0
}
421
422
absl::Status ProtoQualifyState::ApplyLastQualifierGetList(
423
0
    const cel::AttributeQualifier& qualifier, MemoryManagerRef memory_manager) {
424
0
  ABSL_DCHECK(!repeated_field_desc_->is_map());
425
426
0
  absl::StatusOr<int> index = CheckListIndex(qualifier);
427
0
  if (!index.ok()) {
428
0
    SetResultFromError(std::move(index).status(), memory_manager);
429
0
    return absl::OkStatus();
430
0
  }
431
0
  return SetResultFromRepeatedField(message_, repeated_field_desc_, *index,
432
0
                                    memory_manager);
433
0
}
434
435
absl::Status ProtoQualifyState::ApplyLastQualifierGetMap(
436
0
    const cel::AttributeQualifier& qualifier, MemoryManagerRef memory_manager) {
437
0
  ABSL_DCHECK(repeated_field_desc_->is_map());
438
439
0
  absl::StatusOr<google::protobuf::MapValueConstRef> value_ref = CheckMapIndex(qualifier);
440
441
0
  if (!value_ref.ok()) {
442
0
    SetResultFromError(std::move(value_ref).status(), memory_manager);
443
0
    return absl::OkStatus();
444
0
  }
445
446
0
  const auto* value_desc =
447
0
      repeated_field_desc_->message_type()->FindFieldByNumber(kValueTag);
448
0
  return SetResultFromMapField(message_, value_desc, *value_ref,
449
0
                               memory_manager);
450
0
}
451
452
}  // namespace cel::extensions::protobuf_internal