github.com/zntrio/harp/v2@v2.0.9/pkg/bundle/ruleset/ruleset.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package ruleset 19 20 import ( 21 "encoding/base64" 22 "fmt" 23 24 "google.golang.org/protobuf/proto" 25 26 bundlev1 "github.com/zntrio/harp/v2/api/gen/go/harp/bundle/v1" 27 28 "golang.org/x/crypto/blake2b" 29 ) 30 31 // Validate bundle patch. 32 func Validate(spec *bundlev1.RuleSet) error { 33 // Check if spec is nil 34 if spec == nil { 35 return fmt.Errorf("unable to validate bundle patch: patch is nil") 36 } 37 38 if spec.ApiVersion != "harp.elastic.co/v1" { 39 return fmt.Errorf("apiVersion should be 'harp.elastic.co/v1'") 40 } 41 42 if spec.Kind != "RuleSet" { 43 return fmt.Errorf("kind should be 'RuleSet'") 44 } 45 46 if spec.Meta == nil { 47 return fmt.Errorf("meta should be 'nil'") 48 } 49 50 if spec.Spec == nil { 51 return fmt.Errorf("spec should be 'nil'") 52 } 53 54 // No error 55 return nil 56 } 57 58 // Checksum calculates the specification checksum. 59 func Checksum(spec *bundlev1.RuleSet) (string, error) { 60 // Validate bundle template 61 if err := Validate(spec); err != nil { 62 return "", fmt.Errorf("unable to validate spec: %w", err) 63 } 64 65 // Encode spec as protobuf 66 payload, err := proto.Marshal(spec) 67 if err != nil { 68 return "", fmt.Errorf("unable to encode bundle patch: %w", err) 69 } 70 71 // Calculate checksum 72 checksum := blake2b.Sum256(payload) 73 74 // No error 75 return base64.RawURLEncoding.EncodeToString(checksum[:]), nil 76 }