fix: fixed verification endpoint and verification logic for brand fetch (#3470)
Lint / golangci-lint (push) Waiting to run
Lint / semgrep (push) Waiting to run
Release / Release (push) Waiting to run
Scan for secrets / test (push) Waiting to run
Test / test (push) Waiting to run
Test / test-community (push) Waiting to run
Lint / golangci-lint (push) Waiting to run
Lint / semgrep (push) Waiting to run
Release / Release (push) Waiting to run
Scan for secrets / test (push) Waiting to run
Test / test (push) Waiting to run
Test / test-community (push) Waiting to run
* fix: fixed verification endpoint and verification logic * feat: introduced a new detector for apis Signed-off-by: Sahil Silare <[email protected]> * feat: added versioner impl Signed-off-by: Sahil Silare <[email protected]> * refactor: added abstraction Signed-off-by: Sahil Silare <[email protected]> * linter issues fixed * fixed all issues in v1 * brandfetch v2 detector added with pattern tests * fixed brandfetch v2 integration tests * updated the pattern test cases --------- Signed-off-by: Sahil Silare <[email protected]> Co-authored-by: Shahzad Haider <[email protected]> Co-authored-by: Shahzad Haider <[email protected]>
This commit is contained in:
co-authored by
Shahzad Haider
Shahzad Haider
parent
c53f4d3392
commit
ed6d045b46
@@ -0,0 +1,80 @@
|
||||
package brandfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
|
||||
v2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v2"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
|
||||
)
|
||||
|
||||
type Scanner struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func (s Scanner) Version() int { return 1 }
|
||||
|
||||
var (
|
||||
// Ensure the Scanner satisfies the interface at compile time.
|
||||
_ detectors.Detector = (*Scanner)(nil)
|
||||
_ detectors.Versioner = (*Scanner)(nil)
|
||||
defaultClient = common.SaneHttpClient()
|
||||
|
||||
// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
|
||||
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `\b([0-9A-Za-z]{40})\b`)
|
||||
)
|
||||
|
||||
// Keywords are used for efficiently pre-filtering chunks.
|
||||
// Use identifiers in the secret preferably, or the provider name.
|
||||
func (s Scanner) Keywords() []string {
|
||||
return []string{"brandfetch"}
|
||||
}
|
||||
|
||||
func (s Scanner) Type() detectorspb.DetectorType {
|
||||
return detectorspb.DetectorType_Brandfetch
|
||||
}
|
||||
|
||||
func (s Scanner) Description() string {
|
||||
return "Brandfetch is a service that provides brand data, including logos, colors, fonts, and more. Brandfetch API keys can be used to access this data."
|
||||
}
|
||||
|
||||
func (s Scanner) getClient() *http.Client {
|
||||
if s.client != nil {
|
||||
return s.client
|
||||
}
|
||||
|
||||
return defaultClient
|
||||
}
|
||||
|
||||
// FromData will find and optionally verify Brandfetch secrets in a given set of bytes.
|
||||
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
|
||||
dataStr := string(data)
|
||||
|
||||
uniqueTokenMatches := make(map[string]struct{})
|
||||
for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
|
||||
uniqueTokenMatches[match[1]] = struct{}{}
|
||||
}
|
||||
|
||||
for match := range uniqueTokenMatches {
|
||||
s1 := detectors.Result{
|
||||
DetectorType: detectorspb.DetectorType_Brandfetch,
|
||||
Raw: []byte(match),
|
||||
ExtraData: map[string]string{"version": strconv.Itoa(s.Version())},
|
||||
}
|
||||
|
||||
if verify {
|
||||
isVerified, verificationErr := v2.VerifyMatch(ctx, s.getClient(), match)
|
||||
s1.Verified = isVerified
|
||||
s1.SetVerificationError(verificationErr, match)
|
||||
}
|
||||
|
||||
results = append(results, s1)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
+1
@@ -95,6 +95,7 @@ func TestBrandfetch_FromChunk(t *testing.T) {
|
||||
t.Fatalf("no raw secret present: \n %+v", got[i])
|
||||
}
|
||||
got[i].Raw = nil
|
||||
got[i].ExtraData = nil
|
||||
}
|
||||
if diff := pretty.Compare(got, tt.want); diff != "" {
|
||||
t.Errorf("Brandfetch.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
|
||||
+51
-45
@@ -3,8 +3,8 @@ package brandfetch
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
@@ -14,16 +14,20 @@ import (
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
|
||||
)
|
||||
|
||||
type Scanner struct{}
|
||||
type Scanner struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// Ensure the Scanner satisfies the interface at compile time.
|
||||
var _ detectors.Detector = (*Scanner)(nil)
|
||||
func (s Scanner) Version() int { return 2 }
|
||||
|
||||
var (
|
||||
client = common.SaneHttpClient()
|
||||
// Ensure the Scanner satisfies the interface at compile time.
|
||||
_ detectors.Detector = (*Scanner)(nil)
|
||||
_ detectors.Versioner = (*Scanner)(nil)
|
||||
defaultClient = common.SaneHttpClient()
|
||||
|
||||
// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
|
||||
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `\b([0-9A-Za-z]{40})\b`)
|
||||
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"brandfetch"}) + `([a-zA-Z0-9=+/\-_!@#$%^&*()]{43}=)`)
|
||||
)
|
||||
|
||||
// Keywords are used for efficiently pre-filtering chunks.
|
||||
@@ -32,32 +36,6 @@ func (s Scanner) Keywords() []string {
|
||||
return []string{"brandfetch"}
|
||||
}
|
||||
|
||||
// FromData will find and optionally verify Brandfetch secrets in a given set of bytes.
|
||||
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
|
||||
dataStr := string(data)
|
||||
|
||||
matches := keyPat.FindAllStringSubmatch(dataStr, -1)
|
||||
|
||||
for _, match := range matches {
|
||||
resMatch := strings.TrimSpace(match[1])
|
||||
|
||||
s1 := detectors.Result{
|
||||
DetectorType: detectorspb.DetectorType_Brandfetch,
|
||||
Raw: []byte(resMatch),
|
||||
}
|
||||
|
||||
if verify {
|
||||
isVerified, verificationErr := verifyBrandFetch(ctx, client, resMatch)
|
||||
s1.Verified = isVerified
|
||||
s1.SetVerificationError(verificationErr)
|
||||
}
|
||||
|
||||
results = append(results, s1)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (s Scanner) Type() detectorspb.DetectorType {
|
||||
return detectorspb.DetectorType_Brandfetch
|
||||
}
|
||||
@@ -66,29 +44,57 @@ func (s Scanner) Description() string {
|
||||
return "Brandfetch is a service that provides brand data, including logos, colors, fonts, and more. Brandfetch API keys can be used to access this data."
|
||||
}
|
||||
|
||||
// docs: https://docs.brandfetch.com/docs/brand-api#overview
|
||||
func verifyBrandFetch(ctx context.Context, client *http.Client, key string) (bool, error) {
|
||||
payload := strings.NewReader(`{
|
||||
"domain": "www.example.com"
|
||||
}`)
|
||||
func (s Scanner) getClient() *http.Client {
|
||||
if s.client != nil {
|
||||
return s.client
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", "https://api.brandfetch.io/v1/color", payload)
|
||||
return defaultClient
|
||||
}
|
||||
|
||||
// FromData will find and optionally verify Brandfetch secrets in a given set of bytes.
|
||||
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
|
||||
dataStr := string(data)
|
||||
|
||||
uniqueMatches := make(map[string]struct{})
|
||||
for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
|
||||
uniqueMatches[strings.TrimSpace(match[1])] = struct{}{}
|
||||
}
|
||||
|
||||
for match := range uniqueMatches {
|
||||
s1 := detectors.Result{
|
||||
DetectorType: detectorspb.DetectorType_Brandfetch,
|
||||
Raw: []byte(match),
|
||||
ExtraData: map[string]string{"version": strconv.Itoa(s.Version())},
|
||||
}
|
||||
|
||||
if verify {
|
||||
isVerified, verificationErr := VerifyMatch(ctx, s.getClient(), match)
|
||||
s1.Verified = isVerified
|
||||
s1.SetVerificationError(verificationErr, match)
|
||||
}
|
||||
|
||||
results = append(results, s1)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// verifyMatch checks if the provided Brandfetch token is valid by making a request to the Brandfetch API.
|
||||
// https://docs.brandfetch.com/docs/getting-started
|
||||
func VerifyMatch(ctx context.Context, client *http.Client, token string) (bool, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.brandfetch.io/v2/brands/google.com", http.NoBody)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.Header.Add("x-api-key", key)
|
||||
|
||||
req.Header.Add("Authorization", "Bearer "+token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
defer resp.Body.Close()
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build detectors
|
||||
// +build detectors
|
||||
|
||||
package brandfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kylelemons/godebug/pretty"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
|
||||
)
|
||||
|
||||
func TestBrandfetch_FromChunk(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors6")
|
||||
if err != nil {
|
||||
t.Fatalf("could not get test secrets from GCP: %s", err)
|
||||
}
|
||||
secret := testSecrets.MustGetField("BRANDFETCH_V2")
|
||||
inactiveSecret := testSecrets.MustGetField("BRANDFETCH_V2_INACTIVE")
|
||||
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
data []byte
|
||||
verify bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
s Scanner
|
||||
args args
|
||||
want []detectors.Result
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "found, verified",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte(fmt.Sprintf("You can find a brandfetch secret %s within", secret)),
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_Brandfetch,
|
||||
Verified: true,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "found, unverified",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte(fmt.Sprintf("You can find a brandfetch secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation
|
||||
verify: true,
|
||||
},
|
||||
want: []detectors.Result{
|
||||
{
|
||||
DetectorType: detectorspb.DetectorType_Brandfetch,
|
||||
Verified: false,
|
||||
},
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "not found",
|
||||
s: Scanner{},
|
||||
args: args{
|
||||
ctx: context.Background(),
|
||||
data: []byte("You cannot find the secret within"),
|
||||
verify: true,
|
||||
},
|
||||
want: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := Scanner{}
|
||||
got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("Brandfetch.FromData() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
for i := range got {
|
||||
if len(got[i].Raw) == 0 {
|
||||
t.Fatalf("no raw secret present: \n %+v", got[i])
|
||||
}
|
||||
got[i].Raw = nil
|
||||
got[i].ExtraData = nil
|
||||
}
|
||||
if diff := pretty.Compare(got, tt.want); diff != "" {
|
||||
t.Errorf("Brandfetch.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFromData(benchmark *testing.B) {
|
||||
ctx := context.Background()
|
||||
s := Scanner{}
|
||||
for name, data := range detectors.MustGetBenchmarkData() {
|
||||
benchmark.Run(name, func(b *testing.B) {
|
||||
b.ResetTimer()
|
||||
for n := 0; n < b.N; n++ {
|
||||
_, err := s.FromData(ctx, false, data)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package brandfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"
|
||||
)
|
||||
|
||||
func TestBrandFetch_Pattern(t *testing.T) {
|
||||
d := Scanner{}
|
||||
ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "valid pattern",
|
||||
input: "brandfetch credentials: ZUfake+eKo3qNxLDfake/6vqjOtr4fa6u5wShfakes8=",
|
||||
want: []string{"ZUfake+eKo3qNxLDfake/6vqjOtr4fa6u5wShfakes8="},
|
||||
},
|
||||
{
|
||||
name: "valid pattern - assignment format",
|
||||
input: "BRANDFETCH_API_KEY=msCwufakeod43s2ad/D0em/LbIBpZqFAKE9P+H3UTno=",
|
||||
want: []string{"msCwufakeod43s2ad/D0em/LbIBpZqFAKE9P+H3UTno="},
|
||||
},
|
||||
{
|
||||
name: "valid pattern - complex",
|
||||
input: `
|
||||
func main() {
|
||||
url := "https://api.example.com/v1/resource"
|
||||
|
||||
// Create a new request with the secret as a header
|
||||
req, err := http.NewRequest("GET", url, http.NoBody)
|
||||
if err != nil {
|
||||
fmt.Println("Error creating request:", err)
|
||||
return
|
||||
}
|
||||
|
||||
brandfetchAPIKey := "0mWrufake4X1dRfake0mxS+E48ofakesTlyl55raNOs="
|
||||
req.Header.Set("x-api-key", brandfetchAPIKey) // brandfetch secret
|
||||
|
||||
// Perform the request
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check response status
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
fmt.Println("Request successful!")
|
||||
} else {
|
||||
fmt.Println("Request failed with status:", resp.Status)
|
||||
}
|
||||
}
|
||||
`,
|
||||
want: []string{"0mWrufake4X1dRfake0mxS+E48ofakesTlyl55raNOs="},
|
||||
},
|
||||
{
|
||||
name: "valid pattern - xml",
|
||||
input: `
|
||||
<com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>
|
||||
<scope>GLOBAL</scope>
|
||||
<id>{uSiXZ-NMpDW-ZJQFSN-5wkT7SqQ8-mDbr9K2pl}</id>
|
||||
<secret>{brandfetch AQAAABAAA 0mWrufake4X1dRfake0mxS+E48ofakesTlyl55rfake=}</secret>
|
||||
<description>configuration for production</description>
|
||||
<creationDate>2023-05-18T14:32:10Z</creationDate>
|
||||
<owner>jenkins-admin</owner>
|
||||
</com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>
|
||||
`,
|
||||
want: []string{"0mWrufake4X1dRfake0mxS+E48ofakesTlyl55rfake="},
|
||||
},
|
||||
{
|
||||
name: "invalid pattern - wrong length",
|
||||
input: "brandfetch credentials: yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U",
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "invalid pattern - invalid characters",
|
||||
input: "brandfetch credentials: yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U[qy]UeIqnFwILOIlEPyBtJ^fakes=",
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "invalid pattern",
|
||||
input: `
|
||||
func main() {
|
||||
url := "https://api.example.com/v1/resource"
|
||||
|
||||
// Create a new request with the secret as a header
|
||||
req, err := http.NewRequest("GET", url, http.NoBody)
|
||||
if err != nil {
|
||||
fmt.Println("Error creating request:", err)
|
||||
return
|
||||
}
|
||||
|
||||
brandfetchAPIKey := "yUeIqnFwILOIlEPyBt+=JOAdwfQ7sD2uHOAdwf2U[qy]UeIqnFwILOIlEPyBtJ^"
|
||||
req.Header.Set("x-api-key", brandfetchAPIKey) // brandfetch secret
|
||||
|
||||
// Perform the request
|
||||
client := &http.Client{}
|
||||
resp, _ := client.Do(req)
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
`,
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))
|
||||
if len(matchedDetectors) == 0 {
|
||||
t.Errorf("test %q failed: expected keywords %v to be found in the input", test.name, d.Keywords())
|
||||
return
|
||||
}
|
||||
|
||||
results, err := d.FromData(context.Background(), false, []byte(test.input))
|
||||
require.NoError(t, err)
|
||||
|
||||
if len(results) != len(test.want) {
|
||||
t.Errorf("mismatch in result count: expected %d, got %d", len(test.want), len(results))
|
||||
return
|
||||
}
|
||||
|
||||
actual := make(map[string]struct{}, len(results))
|
||||
for _, r := range results {
|
||||
if len(r.RawV2) > 0 {
|
||||
actual[string(r.RawV2)] = struct{}{}
|
||||
} else {
|
||||
actual[string(r.Raw)] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
expected := make(map[string]struct{}, len(test.want))
|
||||
for _, v := range test.want {
|
||||
expected[v] = struct{}{}
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Errorf("%s diff: (-want +got)\n%s", test.name, diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,8 @@ import (
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/box"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/boxoauth"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/braintreepayments"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch"
|
||||
brandfetchv1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v1"
|
||||
brandfetchv2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/brandfetch/v2"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/browserstack"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/browshot"
|
||||
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/bscscan"
|
||||
@@ -966,7 +967,8 @@ func buildDetectorList() []detectors.Detector {
|
||||
&box.Scanner{},
|
||||
&boxoauth.Scanner{},
|
||||
&braintreepayments.Scanner{},
|
||||
&brandfetch.Scanner{},
|
||||
&brandfetchv1.Scanner{},
|
||||
&brandfetchv2.Scanner{},
|
||||
&browserstack.Scanner{},
|
||||
&browshot.Scanner{},
|
||||
&bscscan.Scanner{},
|
||||
|
||||
Reference in New Issue
Block a user