Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions pkg/detectors/aws/access_keys/accesskey.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package access_keys

import (
"maps"
"context"
"fmt"
"net"
Expand Down Expand Up @@ -220,9 +221,7 @@ func (s scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}

// Append the extraData to the existing ExtraData map.
for k, v := range extraData {
s1.ExtraData[k] = v
}
maps.Copy(s1.ExtraData, extraData)
s1.SetVerificationError(verificationErr, secretMatch)
}
}
Expand Down
145 changes: 145 additions & 0 deletions pkg/detectors/castai/castai.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package castai

import (
"context"
"fmt"
"io"
"maps"
"net/http"

regexp "github.com/wasilibs/go-re2"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
)

type scanner struct {
client *http.Client
detectors.EndpointSetter
}

func New(opts ...func(*scanner)) *scanner {
scanner := &scanner{}

// Default endpoints.
_ = scanner.SetConfiguredEndpoints(
"https://api.cast.ai/v1/kubernetes/external-clusters",
"https://api.eu.cast.ai/v1/kubernetes/external-clusters",
)

for _, opt := range opts {
opt(scanner)
}

return scanner
}

func WithClient(c *http.Client) func(*scanner) {
return func(s *scanner) {
s.client = c
}
}

// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*scanner)(nil)
var _ detectors.EndpointCustomizer = (*scanner)(nil)
var _ detectors.Versioner = (*scanner)(nil)

var (
defaultClient = common.SaneHttpClient()
// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.
keyPat = regexp.MustCompile(`\b(castai_v1_[a-z0-9]{64}_[a-z0-9]{8})\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{"castai_v1_"} // Prefix
}

func (scanner) Version() int {
return 1
}

// FromData will find and optionally verify Castai 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[match[1]] = struct{}{}
}

for match := range uniqueMatches {
s1 := detectors.Result{
DetectorType: detector_typepb.DetectorType_CastAI,
Raw: []byte(match),
SecretParts: map[string]string{"key": match},
}

if verify {
client := s.client
if client == nil {
client = defaultClient
}

for _, endpoint := range s.Endpoints() {
isVerified, extraData, verificationErr := verifyMatch(ctx, client, endpoint, match)
// A token can only be valid in a single environment.
if !isVerified && verificationErr == nil {
continue
}

s1.Verified = isVerified
s1.ExtraData = map[string]string{
"endpoint": endpoint,
}
maps.Copy(s1.ExtraData, extraData)
s1.SetVerificationError(verificationErr, match)
break
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verification breaks on first endpoint error, skipping alternatives

Medium Severity

When the first endpoint returns a transient error (timeout, 5xx), the loop breaks immediately without trying the remaining endpoint. A token valid on the EU endpoint would be reported as unverified with an error if the US endpoint happens to be temporarily unreachable, since the continue only fires for definitive 401 responses (!isVerified && verificationErr == nil).

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e828423. Configure here.

}

results = append(results, s1)
}

return
}

func verifyMatch(ctx context.Context, client *http.Client, endpoint string, token string) (bool, map[string]string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return false, nil, err
}

req.Header.Set("X-API-Key", token)

res, err := client.Do(req)
if err != nil {
return false, nil, err
}
defer func() {
_, _ = io.Copy(io.Discard, res.Body)
_ = res.Body.Close()
}()

switch res.StatusCode {
case http.StatusOK:
// If the endpoint returns useful information, we can return it as a map.
return true, nil, nil
case http.StatusUnauthorized:
// The secret is determinately not verified (nothing to do)
return false, nil, nil
default:
return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}

func (s scanner) Type() detector_typepb.DetectorType {
return detector_typepb.DetectorType_CastAI
}

func (s scanner) Description() string {
return "Castai is a blockchain development platform that provides a suite of tools and services for building and scaling decentralized applications. Castai API keys can be used to access these services."
}
170 changes: 170 additions & 0 deletions pkg/detectors/castai/castai_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
//go:build detectors
// +build detectors

package castai

import (
"context"
"fmt"
"testing"
"time"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
)

func TestCastai_FromChunk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}
secret := testSecrets.MustGetField("CASTAI")
inactiveSecret := testSecrets.MustGetField("CASTAI_INACTIVE")

type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s *scanner
args args
want []detectors.Result
wantErr bool
wantVerificationErr bool
}{
{
name: "found, verified",
s: New(),
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a castai secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detector_typepb.DetectorType_CastAI,
Verified: true,
ExtraData: map[string]string{
"endpoint": "https://api.cast.ai/v1/kubernetes/external-clusters",
},
},
},
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, unverified",
s: New(),
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a castai secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation
verify: true,
},
want: []detectors.Result{
{
DetectorType: detector_typepb.DetectorType_CastAI,
Verified: false,
},
},
wantErr: false,
wantVerificationErr: false,
},
{
name: "not found",
s: New(),
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, would be verified if not for timeout",
s: New(WithClient(common.SaneHttpClientTimeOut(1 * time.Microsecond))),
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a castai secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detector_typepb.DetectorType_CastAI,
Verified: false,
ExtraData: map[string]string{
"endpoint": "https://api.cast.ai/v1/kubernetes/external-clusters",
},
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "found, verified but unexpected api surface",
s: New(WithClient(common.ConstantResponseHttpClient(404, ""))),
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a castai secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detector_typepb.DetectorType_CastAI,
Verified: false,
ExtraData: map[string]string{
"endpoint": "https://api.cast.ai/v1/kubernetes/external-clusters",
},
},
},
wantErr: false,
wantVerificationErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("Castai.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])
}
if (got[i].VerificationError() != nil) != tt.wantVerificationErr {
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
}
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError", "primarySecret", "SecretParts")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("Castai.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}
}

func BenchmarkFromData(benchmark *testing.B) {
ctx := context.Background()
s := New()
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)
}
}
})
}
}
Loading