From d31c04eaf9c226b5a1563cdc5b500b9bd5072b53 Mon Sep 17 00:00:00 2001 From: Shahzad Haider <76992801+shahzadhaider1@users.noreply.github.com> Date: Thu, 6 Aug 2026 22:35:37 +0500 Subject: [PATCH] Add Figma Personal Access Token v3 Detector (#4790) * added v3 for figma pat * fix regex pattern and tests in v3 * add verification function in a separate file * add secretparts to results in figma detector * Gate Figma v3 detector behind feature flag * fix failing tests * address review feedback on figma detector * Add unit tests for Figma VerifyMatch * restore comments * verify Figma tokens by parsing the 403 response body --- main.go | 1 + .../figmapersonalaccesstoken.go | 70 +++++++ .../figmapersonalaccesstoken_test.go | 85 +++++++++ .../v1/figmapersonalaccesstoken.go | 48 ++--- ...igmapersonalacesstoken_integration_test.go | 2 +- ...gmapersonalaccesstoken_integration_test.go | 2 +- .../v2/figmapersonalaccesstoken_v2.go | 37 ++-- .../v3/figmapersonalaccesstoken.go | 83 +++++++++ ...gmapersonalaccesstoken_integration_test.go | 171 ++++++++++++++++++ .../v3/figmapersonalaccesstoken_test.go | 122 +++++++++++++ pkg/engine/defaults/defaults.go | 4 + pkg/feature/feature.go | 1 + 12 files changed, 570 insertions(+), 56 deletions(-) create mode 100644 pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken.go create mode 100644 pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken_test.go create mode 100644 pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken.go create mode 100644 pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_integration_test.go create mode 100644 pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_test.go diff --git a/main.go b/main.go index 0681007da..4d62eec96 100644 --- a/main.go +++ b/main.go @@ -543,6 +543,7 @@ func run(state overseer.State, logSync func() error) { feature.PineconeDetectorEnabled.Store(true) feature.CloudinaryDetectorEnabled.Store(true) feature.GitLabOAuthDetectorEnabled.Store(true) + feature.FigmaV3DetectorEnabled.Store(true) feature.SonarCloudV2DetectorEnabled.Store(true) feature.EnigmaDetectorEnabled.Store(true) feature.DatadogApiKeyDetectorEnabled.Store(true) diff --git a/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken.go b/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken.go new file mode 100644 index 000000000..6fe8583be --- /dev/null +++ b/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken.go @@ -0,0 +1,70 @@ +package figmapersonalaccesstoken + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" +) + +// VerifyMatch checks if the provided Figma token is valid by making a request to the Figma API. +// +// Tokens are passed via the X-Figma-Token header: +// https://developers.figma.com/docs/rest-api/personal-access-tokens/ +// +// Figma documents 400, 403, 404, 429 and 500, and returns 403 for every +// authentication failure: https://developers.figma.com/docs/rest-api/errors/ +// We are keeping 401 here for completeness, but it is not documented. +func VerifyMatch(ctx context.Context, client *http.Client, token string) (bool, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.figma.com/v1/me", http.NoBody) + if err != nil { + return false, err + } + + req.Header.Add("X-Figma-Token", token) + res, err := client.Do(req) + if err != nil { + return false, err + } + defer func() { + _, _ = io.Copy(io.Discard, res.Body) + _ = res.Body.Close() + }() + + switch res.StatusCode { + case http.StatusOK: + return true, nil + case http.StatusUnauthorized: + return false, nil + case http.StatusForbidden: + return verify403(res.Body) + default: + return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) + } +} + +// verify403 distinguishes a dead token from a live one. /v1/me requires the +// current_user:read scope (https://developers.figma.com/docs/rest-api/scopes/), +// so a live token issued without it is rejected with the same 403 as a revoked +// one. The error message is the only thing that separates them. +func verify403(body io.Reader) (bool, error) { + var res struct { + Err string `json:"err"` + } + if err := json.NewDecoder(body).Decode(&res); err != nil { + return false, fmt.Errorf("decoding 403 response body: %w", err) + } + + switch { + case res.Err == "Invalid token": + return false, nil + case strings.HasPrefix(res.Err, "Invalid scope(s):"): + return true, nil + default: + // Reported as indeterminate rather than unverified so an unrecognised + // message surfaces instead of silently becoming a false negative. + return false, fmt.Errorf("unexpected 403 response: %q", res.Err) + } +} diff --git a/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken_test.go b/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken_test.go new file mode 100644 index 000000000..5c1cf0b87 --- /dev/null +++ b/pkg/detectors/figmapersonalaccesstoken/figmapersonalaccesstoken_test.go @@ -0,0 +1,85 @@ +package figmapersonalaccesstoken + +import ( + "context" + "testing" + + "github.com/trufflesecurity/trufflehog/v3/pkg/common" +) + +func TestVerifyMatch(t *testing.T) { + tests := []struct { + name string + statusCode int + body string + wantVerified bool + wantErr bool + }{ + { + name: "200 OK is verified", + statusCode: 200, + wantVerified: true, + wantErr: false, + }, + { + name: "403 invalid token is unverified without error", + statusCode: 403, + body: `{"status":403,"err":"Invalid token"}`, + wantVerified: false, + wantErr: false, + }, + { + name: "403 missing scope is a live token", + statusCode: 403, + body: `{"status":403,"err":"Invalid scope(s): file_comments:read. This endpoint requires the current_user:read scope"}`, + wantVerified: true, + wantErr: false, + }, + { + name: "403 with an unrecognised message is indeterminate", + statusCode: 403, + body: `{"status":403,"err":"Request denied"}`, + wantVerified: false, + wantErr: true, + }, + { + name: "403 with an unparseable body is indeterminate", + statusCode: 403, + body: "not json", + wantVerified: false, + wantErr: true, + }, + { + name: "401 Unauthorized is unverified with no error", + statusCode: 401, + wantVerified: false, + wantErr: false, + }, + { + name: "429 rate limited is unverified with error", + statusCode: 429, + wantVerified: false, + wantErr: true, + }, + { + name: "500 Internal Server Error is unverified with error", + statusCode: 500, + wantVerified: false, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + client := common.ConstantResponseHttpClient(tt.statusCode, tt.body) + verified, err := VerifyMatch(context.Background(), client, "figp_test_token") + + if verified != tt.wantVerified { + t.Errorf("VerifyMatch() verified = %v, want %v", verified, tt.wantVerified) + } + if (err != nil) != tt.wantErr { + t.Errorf("VerifyMatch() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalaccesstoken.go b/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalaccesstoken.go index 3d01872cc..be0e36a0d 100644 --- a/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalaccesstoken.go +++ b/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalaccesstoken.go @@ -10,6 +10,7 @@ import ( "github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + figma "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" ) @@ -25,8 +26,7 @@ func (Scanner) Version() int { return 1 } var ( defaultClient = common.SaneHttpClient() - - keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"figma"}) + `\b([0-9]{6}-[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12})\b`) + keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"figma"}) + `\b([0-9]{6}-[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12})\b`) ) // Keywords are used for efficiently pre-filtering chunks. @@ -35,6 +35,17 @@ func (s Scanner) Keywords() []string { return []string{"figma"} } +func (s Scanner) Description() string { + return "Figma is a web-based design tool. Personal Access Tokens can be used to access and modify design files and other resources." +} + +func (s Scanner) getClient() *http.Client { + if s.client != nil { + return s.client + } + return defaultClient +} + // FromData will find and optionally verify FigmaPersonalAccessToken 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) @@ -45,37 +56,18 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result resMatch := strings.TrimSpace(match[1]) s1 := detectors.Result{ - DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + DetectorType: s.Type(), Raw: []byte(resMatch), ExtraData: map[string]string{ - "version": fmt.Sprintf("%d", s.Version()), + "version": fmt.Sprint(s.Version()), }, SecretParts: map[string]string{"token": resMatch}, } if verify { - client := s.client - if client == nil { - client = defaultClient - } - - req, err := http.NewRequestWithContext(ctx, "GET", "https://api.figma.com/v1/me", nil) - if err != nil { - continue - } - req.Header.Add("X-Figma-Token", resMatch) - res, err := client.Do(req) - if err == nil { - defer func() { _ = res.Body.Close() }() - if res.StatusCode >= 200 && res.StatusCode < 300 { - s1.Verified = true - } else if res.StatusCode != 403 { - err = fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) - s1.SetVerificationError(err, resMatch) - } - } else { - s1.SetVerificationError(err, resMatch) - } + isVerified, verificationErr := figma.VerifyMatch(ctx, s.getClient(), resMatch) + s1.Verified = isVerified + s1.SetVerificationError(verificationErr, resMatch) } results = append(results, s1) @@ -87,7 +79,3 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result func (s Scanner) Type() detector_typepb.DetectorType { return detector_typepb.DetectorType_FigmaPersonalAccessToken } - -func (s Scanner) Description() string { - return "Figma is a web-based design tool. Personal Access Tokens can be used to access and modify design files and other resources." -} diff --git a/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalacesstoken_integration_test.go b/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalacesstoken_integration_test.go index a05e63fbc..bc5c84fd5 100644 --- a/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalacesstoken_integration_test.go +++ b/pkg/detectors/figmapersonalaccesstoken/v1/figmapersonalacesstoken_integration_test.go @@ -145,7 +145,7 @@ func TestFigmaPersonalAccessToken_FromChunk(t *testing.T) { t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError()) } } - ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError") + ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError", "primarySecret", "SecretParts", "chunkOffset", "chunkOffsetSet") if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" { t.Errorf("FigmaPersonalAccessToken.FromData() %s diff: (-got +want)\n%s", tt.name, diff) } diff --git a/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_integration_test.go b/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_integration_test.go index d9da51d71..fb33efe4b 100644 --- a/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_integration_test.go +++ b/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_integration_test.go @@ -145,7 +145,7 @@ func TestFigmaPersonalAccessToken_FromChunk(t *testing.T) { t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError()) } } - ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError") + ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError", "primarySecret", "SecretParts", "chunkOffset", "chunkOffsetSet") if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" { t.Errorf("FigmaPersonalAccessToken.FromData() %s diff: (-got +want)\n%s", tt.name, diff) } diff --git a/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_v2.go b/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_v2.go index 5dc5ba4ff..af93b0440 100644 --- a/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_v2.go +++ b/pkg/detectors/figmapersonalaccesstoken/v2/figmapersonalaccesstoken_v2.go @@ -10,6 +10,7 @@ import ( "github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + figma "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" ) @@ -39,6 +40,13 @@ func (s Scanner) Description() string { return "Figma is a collaborative interface design tool. Figma Personal Access Tokens can be used to access and manipulate design files and other resources on behalf of a user." } +func (s Scanner) getClient() *http.Client { + if s.client != nil { + return s.client + } + return defaultClient +} + // FromData will find and optionally verify FigmaPersonalAccessToken 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) @@ -49,37 +57,18 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result resMatch := strings.TrimSpace(match[1]) s1 := detectors.Result{ - DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + DetectorType: s.Type(), Raw: []byte(resMatch), ExtraData: map[string]string{ - "version": fmt.Sprintf("%d", s.Version()), + "version": fmt.Sprint(s.Version()), }, SecretParts: map[string]string{"token": resMatch}, } if verify { - client := s.client - if client == nil { - client = defaultClient - } - - req, err := http.NewRequestWithContext(ctx, "GET", "https://api.figma.com/v1/me", nil) - if err != nil { - continue - } - req.Header.Add("X-Figma-Token", resMatch) - res, err := client.Do(req) - if err == nil { - defer func() { _ = res.Body.Close() }() - if res.StatusCode >= 200 && res.StatusCode < 300 { - s1.Verified = true - } else if res.StatusCode != 403 { - err = fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) - s1.SetVerificationError(err, resMatch) - } - } else { - s1.SetVerificationError(err, resMatch) - } + isVerified, verificationErr := figma.VerifyMatch(ctx, s.getClient(), resMatch) + s1.Verified = isVerified + s1.SetVerificationError(verificationErr, resMatch) } results = append(results, s1) diff --git a/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken.go b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken.go new file mode 100644 index 000000000..642847e26 --- /dev/null +++ b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken.go @@ -0,0 +1,83 @@ +package figmapersonalaccesstoken + +import ( + "context" + "fmt" + "net/http" + "strings" + + regexp "github.com/wasilibs/go-re2" + + "github.com/trufflesecurity/trufflehog/v3/pkg/common" + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + figma "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken" + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" +) + +type Scanner struct { + client *http.Client +} + +var _ detectors.Detector = (*Scanner)(nil) +var _ detectors.Versioner = (*Scanner)(nil) + +func (Scanner) Version() int { return 3 } + +var ( + defaultClient = common.SaneHttpClient() + // The figp_ token charset includes '=' and '-', which are not word characters, + // so a \b word boundary can't be used to anchor the end of the match. Instead we + // require the next character to be outside the token charset (or end of input). + keyPat = regexp.MustCompile(`(figp_[a-zA-Z0-9_=-]{40,54})(?:[^a-zA-Z0-9_=-]|\z)`) +) + +// 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{"figp_"} +} + +func (s Scanner) Description() string { + return "Figma is a collaborative interface design tool. Figma Personal Access Tokens can be used to access and manipulate design files and other resources on behalf of a user." +} + +func (s Scanner) getClient() *http.Client { + if s.client != nil { + return s.client + } + return defaultClient +} + +// FromData will find and optionally verify FigmaPersonalAccessToken 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: s.Type(), + Raw: []byte(resMatch), + ExtraData: map[string]string{ + "version": fmt.Sprint(s.Version()), + }, + SecretParts: map[string]string{"token": resMatch}, + } + + if verify { + isVerified, verificationErr := figma.VerifyMatch(ctx, s.getClient(), resMatch) + s1.Verified = isVerified + s1.SetVerificationError(verificationErr, resMatch) + } + + results = append(results, s1) + } + + return results, nil +} + +func (s Scanner) Type() detector_typepb.DetectorType { + return detector_typepb.DetectorType_FigmaPersonalAccessToken +} diff --git a/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_integration_test.go b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_integration_test.go new file mode 100644 index 000000000..1c9f81db7 --- /dev/null +++ b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_integration_test.go @@ -0,0 +1,171 @@ +//go:build detectors +// +build detectors + +package figmapersonalaccesstoken + +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 TestFigmaPersonalAccessToken_FromChunk(t *testing.T) { + t.Skip("skipping until v3 secrets are provisioned in GCP") + 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("FIGMAPERSONALACCESSTOKEN_V3_TOKEN") + inactiveSecret := testSecrets.MustGetField("FIGMAPERSONALACCESSTOKEN_V3_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: Scanner{}, + args: args{ + ctx: context.Background(), + data: []byte(fmt.Sprintf("You can find a figmapersonalaccesstoken secret %s within", secret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + Verified: true, + ExtraData: map[string]string{ + "version": "3", + }, + }, + }, + wantErr: false, + }, + { + name: "found, unverified", + s: Scanner{}, + args: args{ + ctx: context.Background(), + data: []byte(fmt.Sprintf("You can find a figmapersonalaccesstoken secret %s within but not valid", inactiveSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + Verified: false, + ExtraData: map[string]string{ + "version": "3", + }, + }, + }, + wantErr: false, + }, + { + name: "found, verified but unexpected api surface", + s: Scanner{client: common.ConstantResponseHttpClient(404, "")}, + args: args{ + ctx: context.Background(), + data: []byte(fmt.Sprintf("You can find a figmapersonalaccesstoken secret %s within", secret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + Verified: false, + ExtraData: map[string]string{ + "version": "3", + }, + }, + }, + wantErr: false, + wantVerificationErr: true, + }, + { + name: "found, would be verified if not for timeout", + s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)}, + args: args{ + ctx: context.Background(), + data: []byte(fmt.Sprintf("You can find a figmapersonalaccesstoken secret %s within", secret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_FigmaPersonalAccessToken, + Verified: false, + ExtraData: map[string]string{ + "version": "3", + }, + }, + }, + wantErr: false, + wantVerificationErr: true, + }, + { + 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) { + got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data) + if (err != nil) != tt.wantErr { + t.Errorf("FigmaPersonalAccessToken.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", "verificationError", "primarySecret", "SecretParts", "chunkOffset", "chunkOffsetSet") + if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" { + t.Errorf("FigmaPersonalAccessToken.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) + } + } + }) + } +} diff --git a/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_test.go b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_test.go new file mode 100644 index 000000000..534a87d42 --- /dev/null +++ b/pkg/detectors/figmapersonalaccesstoken/v3/figmapersonalaccesstoken_test.go @@ -0,0 +1,122 @@ +package figmapersonalaccesstoken + +import ( + "context" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick" +) + +var ( + validPattern = `[{ + "_id": "1a8d0cca-e1a9-4318-bc2f-f5658ab2dcb5", + "name": "FigmaV3", + "type": "Detector", + "api": true, + "authentication_type": "", + "verification_url": "https://api.figma.com/v1/me", + "test_secrets": { + "figma_secret": "figp_EZe7plhYvN92IyiDCjkvTcbNVZsuRVpDcHOwNNP1" + }, + "expected_response": "200", + "method": "GET", + "deprecated": false + }]` + secret = "figp_EZe7plhYvN92IyiDCjkvTcbNVZsuRVpDcHOwNNP1" + + // A token ending in '=' or '-' can't be anchored with \b, so keyPat requires the + // next character to fall outside the token charset instead. + secretWithTrailingPadding = "figp_EZe7plhYvN92IyiDCjkvTcbNVZsuRVpDcHOwNN==" + + invalidPatterns = []string{ + `figp_short`, // too short + `figd_EZe7plhYvN92IyiDCjkvTcbNVZsuRVpDcHOwNNP1`, // wrong prefix (v2 token) + `figp_!!!invalid_chars_here!!!!!!!!!!!!!!!!!!!!!!!!!`, // invalid characters + `figp_` + strings.Repeat("a", 60), // over-length, must not match a truncated prefix + } +) + +func TestFigmaPersonalAccessToken_Pattern(t *testing.T) { + d := Scanner{} + ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d}) + + tests := []struct { + name string + input string + want []string + }{ + { + name: "valid pattern", + input: validPattern, + want: []string{secret}, + }, + { + name: "token ending in padding characters", + input: `FigmaAuthToken=` + secretWithTrailingPadding, + want: []string{secretWithTrailingPadding}, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input)) + if len(matchedDetectors) == 0 { + t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input) + return + } + + results, err := d.FromData(context.Background(), false, []byte(test.input)) + if err != nil { + t.Errorf("error = %v", err) + return + } + + if len(results) != len(test.want) { + if len(results) == 0 { + t.Errorf("did not receive result") + } else { + t.Errorf("expected %d results, only received %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) + } + }) + } +} + +func TestFigmaPersonalAccessToken_InvalidPatterns(t *testing.T) { + d := Scanner{} + + for _, input := range invalidPatterns { + t.Run(input, func(t *testing.T) { + results, err := d.FromData(context.Background(), false, []byte(input)) + if err != nil { + t.Errorf("error = %v", err) + return + } + if len(results) != 0 { + t.Errorf("expected no results for invalid input %q, got %d", input, len(results)) + } + }) + } +} diff --git a/pkg/engine/defaults/defaults.go b/pkg/engine/defaults/defaults.go index 7a4913d72..8d9ec8696 100644 --- a/pkg/engine/defaults/defaults.go +++ b/pkg/engine/defaults/defaults.go @@ -292,6 +292,7 @@ import ( "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/fibery" figmapersonalaccesstokenv1 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken/v1" figmapersonalaccesstokenv2 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken/v2" + figmapersonalaccesstokenv3 "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/figmapersonalaccesstoken/v3" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/fileio" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/finage" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/financialmodelingprep" @@ -1199,6 +1200,7 @@ func buildDetectorList() []detectors.Detector { &fibery.Scanner{}, &figmapersonalaccesstokenv1.Scanner{}, &figmapersonalaccesstokenv2.Scanner{}, + &figmapersonalaccesstokenv3.Scanner{}, &fileio.Scanner{}, &finage.Scanner{}, &financialmodelingprep.Scanner{}, @@ -1832,6 +1834,8 @@ func buildDetectorList() []detectors.Detector { return !feature.CloudinaryDetectorEnabled.Load() case *gitlaboauth2.Scanner: return !feature.GitLabOAuthDetectorEnabled.Load() + case *figmapersonalaccesstokenv3.Scanner: + return !feature.FigmaV3DetectorEnabled.Load() case *sonarcloudv2.Scanner: return !feature.SonarCloudV2DetectorEnabled.Load() case *enigma.Scanner: diff --git a/pkg/feature/feature.go b/pkg/feature/feature.go index bf460efb1..613b296c2 100644 --- a/pkg/feature/feature.go +++ b/pkg/feature/feature.go @@ -42,6 +42,7 @@ var ( CloudflareApiTokenV2DetectorEnabled atomic.Bool CloudflareGlobalApiKeyV2DetectorEnabled atomic.Bool DuoDetectorEnabled atomic.Bool + FigmaV3DetectorEnabled atomic.Bool NewRelicLicenseKeyDetectorEnabled atomic.Bool NewRelicBrowserKeyDetectorEnabled atomic.Bool NewRelicUserKeyDetectorEnabled atomic.Bool