1 // Copyright 2022 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 ///////////////////////////////////////////////////////////////////////////////
16 #ifndef TINK_INTERNAL_MONITORING_UTIL_H_
17 #define TINK_INTERNAL_MONITORING_UTIL_H_
18
19 #include <string>
20 #include <vector>
21
22 #include "absl/container/flat_hash_map.h"
23 #include "absl/status/status.h"
24 #include "absl/strings/strip.h"
25 #include "tink/internal/key_status_util.h"
26 #include "tink/key_status.h"
27 #include "tink/monitoring/monitoring.h"
28 #include "tink/primitive_set.h"
29 #include "tink/util/status.h"
30 #include "tink/util/statusor.h"
31 #include "proto/tink.pb.h"
32
33 namespace crypto {
34 namespace tink {
35 namespace internal {
36
37 constexpr char kKeyTypePrefix[] = "type.googleapis.com/google.crypto.";
38
39 // Constructs a MonitoringKeySetInfo object from a PrimitiveSet `primitive_set`
40 // for a given primitive P.
41 template <class P>
42 crypto::tink::util::StatusOr<MonitoringKeySetInfo>
MonitoringKeySetInfoFromPrimitiveSet(const PrimitiveSet<P> & primitive_set)43 MonitoringKeySetInfoFromPrimitiveSet(const PrimitiveSet<P>& primitive_set) {
44 const std::vector<typename PrimitiveSet<P>::template Entry<P>*>
45 primitive_set_entries = primitive_set.get_all();
46 if (primitive_set_entries.empty()) {
47 return util::Status(absl::StatusCode::kInvalidArgument,
48 "The primitive set is empty");
49 }
50 if (primitive_set.get_primary() == nullptr) {
51 return util::Status(absl::StatusCode::kInvalidArgument,
52 "The primary keys must not be null");
53 }
54 std::vector<MonitoringKeySetInfo::Entry> keyset_info_entries = {};
55 for (const auto& entry : primitive_set_entries) {
56 util::StatusOr<KeyStatus> key_status =
57 FromKeyStatusType(entry->get_status());
58 if (!key_status.ok()) return key_status.status();
59
60 auto keyset_info_entry = MonitoringKeySetInfo::Entry(
61 *key_status, entry->get_key_id(),
62 absl::StripPrefix(entry->get_key_type_url(), kKeyTypePrefix),
63 OutputPrefixType_Name(entry->get_output_prefix_type()));
64 keyset_info_entries.push_back(keyset_info_entry);
65 }
66 MonitoringKeySetInfo keyset_info(primitive_set.get_annotations(),
67 keyset_info_entries,
68 primitive_set.get_primary()->get_key_id());
69 return keyset_info;
70 }
71
72 } // namespace internal
73 } // namespace tink
74 } // namespace crypto
75
76 #endif // TINK_INTERNAL_MONITORING_UTIL_H_
77