github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/report/maskprinter.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package report 21 22 import ( 23 "encoding/base64" 24 "io" 25 26 corev1 "k8s.io/api/core/v1" 27 "k8s.io/apimachinery/pkg/api/meta" 28 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 29 "k8s.io/apimachinery/pkg/runtime" 30 "k8s.io/cli-runtime/pkg/printers" 31 ) 32 33 var _ printers.ResourcePrinter = &MaskPrinter{} 34 35 const ( 36 EncryptedData = "KUBE_BLOCKS_ENCRYPTED_DATA" 37 ) 38 39 type MaskPrinter struct { 40 Delegate printers.ResourcePrinter 41 } 42 43 func (p *MaskPrinter) PrintObj(obj runtime.Object, w io.Writer) error { 44 if obj == nil { 45 return p.Delegate.PrintObj(obj, w) 46 } 47 if meta.IsListType(obj) { 48 obj = obj.DeepCopyObject() 49 _ = meta.EachListItem(obj, func(item runtime.Object) error { 50 maskDataField(item) 51 return nil 52 }) 53 } else if _, err := meta.Accessor(obj); err == nil { 54 obj = maskDataField(obj.DeepCopyObject()) 55 } 56 return p.Delegate.PrintObj(obj, w) 57 } 58 59 func maskDataField(o runtime.Object) runtime.Object { 60 objKind := o.GetObjectKind().GroupVersionKind().Kind 61 if objKind == "Secret" || objKind == "ConfigMap" { 62 switch o := o.(type) { 63 case *corev1.Secret: 64 for k := range o.Data { 65 o.Data[k] = []byte(EncryptedData) 66 } 67 case *corev1.ConfigMap: 68 for k := range o.Data { 69 o.Data[k] = EncryptedData 70 } 71 case *unstructured.Unstructured: 72 data := o.Object["data"] 73 if data == nil { 74 return o 75 } 76 if data := data.(map[string]interface{}); data != nil { 77 for k := range data { 78 if objKind == "Secret" { 79 data[k] = base64.StdEncoding.EncodeToString([]byte(EncryptedData)) 80 } else { 81 data[k] = EncryptedData 82 } 83 } 84 } 85 } 86 } 87 return o 88 }