github.com/google/osv-scalibr@v0.4.1/veles/velestest/fakedetector.go (about)

     1  // Copyright 2025 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  package velestest
    16  
    17  import (
    18  	"bytes"
    19  
    20  	"github.com/google/osv-scalibr/veles"
    21  )
    22  
    23  var _ veles.Detector = &FakeDetector{}
    24  
    25  // FakeDetector is a veles.Detector that finds all occurrences of a specific
    26  // Hotword and returns corresponding instances of FakeStringSecret.
    27  type FakeDetector struct {
    28  	Hotword []byte
    29  }
    30  
    31  // NewFakeDetector creates a new FakeDetector using the given hotword.
    32  func NewFakeDetector(hotword string) *FakeDetector {
    33  	return &FakeDetector{Hotword: []byte(hotword)}
    34  }
    35  
    36  // MaxSecretLen returns the maximum length a secret found by the Detector can
    37  // have.
    38  func (d *FakeDetector) MaxSecretLen() uint32 {
    39  	return uint32(len(d.Hotword))
    40  }
    41  
    42  // Detect finds instances of the Hotword in data and returns corresponding
    43  // FakeStringSecrets alongside the starting positions of the matches.
    44  func (d *FakeDetector) Detect(data []byte) ([]veles.Secret, []int) {
    45  	var secrets []veles.Secret
    46  	var positions []int
    47  	offset := 0
    48  	p := bytes.Index(data[offset:], d.Hotword)
    49  	for p != -1 {
    50  		secrets = append(secrets, NewFakeStringSecret(string(d.Hotword)))
    51  		positions = append(positions, offset+p)
    52  		offset += p + len(d.Hotword)
    53  		p = bytes.Index(data[offset:], d.Hotword)
    54  	}
    55  	return secrets, positions
    56  }
    57  
    58  // FakeDetectors creates a slice of FakeDetectors each with a separate hotword
    59  // from hotwords.
    60  func FakeDetectors(hotwords ...string) []veles.Detector {
    61  	var ds []veles.Detector
    62  	for _, hotword := range hotwords {
    63  		ds = append(ds, NewFakeDetector(hotword))
    64  	}
    65  	return ds
    66  }