github.com/google/osv-scalibr@v0.4.1/veles/secrets/common/simpletoken/simpletoken.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 simpletoken contains a Detector for tokens that can be extracted by
    16  // scanning a byte array with a regular expression.
    17  package simpletoken
    18  
    19  import (
    20  	"regexp"
    21  
    22  	"github.com/google/osv-scalibr/veles"
    23  )
    24  
    25  // Detector finds instances of a simple token that matches the regular
    26  // expression Re inside a chunk of text.
    27  // It implements veles.Detector.
    28  type Detector struct {
    29  	// The maximum length of the token.
    30  	MaxLen uint32
    31  	// Matches on the token.
    32  	Re *regexp.Regexp
    33  	// Returns a veles.Secret from a regexp match.
    34  	//  It returns the secret and a boolean indicating success.
    35  	FromMatch func([]byte) (veles.Secret, bool)
    36  }
    37  
    38  // MaxSecretLen returns the maximum length of the token.
    39  func (d Detector) MaxSecretLen() uint32 {
    40  	return d.MaxLen
    41  }
    42  
    43  // Detect finds candidate tokens that match Detector.Re and returns them
    44  // alongside their starting positions.
    45  func (d Detector) Detect(data []byte) (secrets []veles.Secret, positions []int) {
    46  	for _, m := range d.Re.FindAllIndex(data, -1) {
    47  		l, r := m[0], m[1]
    48  		if match, ok := d.FromMatch(data[l:r]); ok {
    49  			secrets = append(secrets, match)
    50  			positions = append(positions, l)
    51  		}
    52  	}
    53  	return secrets, positions
    54  }