Skip to content

Commit

Permalink
fix(golang): handle sprintf properly (#1503)
Browse files Browse the repository at this point in the history
  • Loading branch information
cfabianski authored Feb 19, 2024
1 parent 97c3012 commit b3942b4
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions internal/languages/golang/detectors/string/string.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package string

import (
"fmt"
"regexp"

"github.com/bearer/bearer/internal/scanner/ast/query"
"github.com/bearer/bearer/internal/scanner/ast/tree"
"github.com/bearer/bearer/internal/scanner/ruleset"
Expand All @@ -10,6 +13,11 @@ import (
"github.com/bearer/bearer/internal/scanner/detectors/types"
)

var (
simpleInterpolationRegexp = regexp.MustCompile(`%#?[a-zA-Z]`)
numericInterpolationRegexp = regexp.MustCompile(`%\d?\.?\d?f`)
)

type stringDetector struct {
types.DetectorBase
}
Expand All @@ -27,6 +35,50 @@ func (detector *stringDetector) DetectAt(
detectorContext types.Context,
) ([]interface{}, error) {
switch node.Type() {
case "call_expression":
function := node.ChildByFieldName("function")
if function.Type() == "selector_expression" {
field := function.ChildByFieldName("field")
if field.Type() == "field_identifier" && field.Content() == "Sprintf" {
arguments := node.ChildByFieldName("arguments").NamedChildren()

stringValue, isLiteral, err := common.GetStringValue(arguments[0], detectorContext)
if err != nil || !isLiteral {
return nil, err
}

stringValue = simpleInterpolationRegexp.ReplaceAllString(stringValue, "%s") // %s %d %#v %t
stringValue = numericInterpolationRegexp.ReplaceAllString(stringValue, "%s") // %2.2f %.2f %2f %2.f

newArguments := []any{}
for index, argument := range arguments {
if index == 0 {
continue
}

childValue, childIsLiteral, err := common.GetStringValue(argument, detectorContext)
if err != nil {
return nil, err
}

if !childIsLiteral {
isLiteral = false
if childValue == "" {
childValue = common.NonLiteralValue
}
}

newArguments = append(newArguments, childValue)
}

value := fmt.Sprintf(stringValue, newArguments...)

return []interface{}{common.String{
Value: value,
IsLiteral: isLiteral,
}}, nil
}
}
case "binary_expression":
if node.Children()[1].Content() == "+" {
return common.ConcatenateChildStrings(node, detectorContext)
Expand Down

0 comments on commit b3942b4

Please sign in to comment.