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 17// Package monitoringutil implements utility functions for monitoring. 18package monitoringutil 19 20import ( 21 "fmt" 22 "strings" 23 24 "github.com/google/tink/go/core/primitiveset" 25 "github.com/google/tink/go/monitoring" 26 tpb "github.com/google/tink/go/proto/tink_go_proto" 27) 28 29const keytypeURLPrefix = "type.googleapis.com/google.crypto." 30 31// DoNothingLogger is a Logger that does nothing when invoked. 32type DoNothingLogger struct{} 33 34var _ monitoring.Logger = (*DoNothingLogger)(nil) 35 36// Log drops a log call. 37func (l *DoNothingLogger) Log(uint32, int) {} 38 39// LogFailure drops a failure call. 40func (l *DoNothingLogger) LogFailure() {} 41 42func keyStatusFromProto(status tpb.KeyStatusType) (monitoring.KeyStatus, error) { 43 var keyStatus monitoring.KeyStatus = 55 44 switch status { 45 case tpb.KeyStatusType_ENABLED: 46 keyStatus = monitoring.Enabled 47 case tpb.KeyStatusType_DISABLED: 48 keyStatus = monitoring.Disabled 49 case tpb.KeyStatusType_DESTROYED: 50 keyStatus = monitoring.Destroyed 51 default: 52 return keyStatus, fmt.Errorf("unknown key status: %q", status) 53 } 54 return keyStatus, nil 55 56} 57 58func parseKeyTypeURL(ktu string) string { 59 return strings.TrimPrefix(ktu, keytypeURLPrefix) 60} 61 62// KeysetInfoFromPrimitiveSet creates a `KeysetInfo` from a `PrimitiveSet`. 63// This function doesn't guarantee to preserve the ordering of the keys in the keyset. 64func KeysetInfoFromPrimitiveSet(ps *primitiveset.PrimitiveSet) (*monitoring.KeysetInfo, error) { 65 if ps == nil { 66 return nil, fmt.Errorf("primitive set is nil") 67 } 68 if len(ps.Entries) == 0 { 69 return nil, fmt.Errorf("primitive set is empty") 70 } 71 if ps.Primary == nil { 72 return nil, fmt.Errorf("primary key must not be nil") 73 } 74 entries := []*monitoring.Entry{} 75 for _, pse := range ps.Entries { 76 for _, pe := range pse { 77 keyStatus, err := keyStatusFromProto(pe.Status) 78 if err != nil { 79 return nil, err 80 } 81 e := &monitoring.Entry{ 82 KeyID: pe.KeyID, 83 Status: keyStatus, 84 KeyType: parseKeyTypeURL(pe.TypeURL), 85 KeyPrefix: pe.PrefixType.String(), 86 } 87 entries = append(entries, e) 88 } 89 } 90 return &monitoring.KeysetInfo{ 91 Annotations: ps.Annotations, 92 PrimaryKeyID: ps.Primary.KeyID, 93 Entries: entries, 94 }, nil 95} 96