-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Add support for detecting and validating CastAI API tokens #4926
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
patrickpichler
wants to merge
1
commit into
trufflesecurity:main
Choose a base branch
from
patrickpichler:add-castai-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } | ||
|
|
||
| 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." | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
continueonly fires for definitive 401 responses (!isVerified && verificationErr == nil).Reviewed by Cursor Bugbot for commit e828423. Configure here.