Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[INS-320] Cloudinary detector (#4747)
Muneeb Ullah Khan8a12e8e2fb6f
diff --git a/pkg/detectors/cloudinary/cloudinary.go b/pkg/detectors/cloudinary/cloudinary.gonew file mode 100644index 000000000..6db54f3af--- /dev/null+++ b/pkg/detectors/cloudinary/cloudinary.go@@ -0,0 +1,134 @@+package cloudinary++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "path"++ 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.DefaultMultiPartCredentialProvider+}++// Ensure the Scanner satisfies the interface at compile time.+var _ detectors.Detector = (*Scanner)(nil)++var (+ defaultClient = common.SaneHttpClient()++ // Cloudinary cloud names are typically b/w 3-50 characters.+ // This regex matches cloud names that appear near the word "cloudinary" and either the keyword "name" or "@" (as in URLs).+ cloudnamePat = regexp.MustCompile(`(?i:cloudinary)(?:.|[\n\r]){0,47}?` + `(?i:name|@)(?:.){0,10}?` + `\b([a-zA-Z][a-zA-Z0-9-]{2,49})\b`)++ // Cloudinary API keys are numeric and typically 15 digits long.+ apiKeyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"cloudinary"}) + `\b(\d{15})\b`)++ // Cloudinary API secrets are typically 27 characters long and may contain+ // uppercase letters, lowercase letters, digits, underscores, or hyphens.+ apiSecretPat = regexp.MustCompile(detectors.PrefixRegex([]string{"cloudinary"}) + `\b([A-Za-z0-9_-]{27})\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{"cloudinary"}+}++func (s Scanner) getClient() *http.Client {+ if s.client != nil {+ return s.client+ }+ return defaultClient+}++// FromData will find and optionally verify DeepSeek 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)++ uniqueCloudNames := make(map[string]struct{})+ uniqueApiKeys := make(map[string]struct{})+ uniqueApiSecret := make(map[string]struct{})+ for _, match := range cloudnamePat.FindAllStringSubmatch(dataStr, -1) {+ uniqueCloudNames[match[1]] = struct{}{}+ }+ for _, match := range apiKeyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueApiKeys[match[1]] = struct{}{}+ }+ for _, match := range apiSecretPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueApiSecret[match[1]] = struct{}{}+ }+ for cloudName := range uniqueCloudNames {+ for apiKey := range uniqueApiKeys {+ for apiSecret := range uniqueApiSecret {+ s1 := detectors.Result{+ DetectorType: detector_typepb.DetectorType_Cloudinary,+ Raw: []byte(apiKey),+ RawV2: []byte(fmt.Sprintf("%s:%s:%s", cloudName, apiKey, apiSecret)),+ SecretParts: map[string]string{+ "cloud_name": cloudName,+ "api_key": apiKey,+ "api_secret": apiSecret,+ },+ }+ if verify {+ verified, verificationErr := verifyToken(ctx, s.getClient(), cloudName, apiKey, apiSecret)+ s1.SetVerificationError(verificationErr, cloudName, apiKey, apiSecret)+ s1.Verified = verified+ }+ results = append(results, s1)+ }+ }+ }+ return+}++func verifyToken(ctx context.Context, client *http.Client, cloudName, apiKey, apiSecret string) (bool, error) {+ u := &url.URL{+ Scheme: "https",+ Host: "api.cloudinary.com",+ Path: path.Join("v1_1", cloudName, "usage"),+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody)+ if err != nil {+ return false, err+ }++ req.SetBasicAuth(apiKey, apiSecret)++ 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:+ // Invalid+ return false, nil+ default:+ return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)+ }+}++func (s Scanner) Type() detector_typepb.DetectorType {+ return detector_typepb.DetectorType_Cloudinary+}++func (s Scanner) Description() string {+ return "Cloudinary is a cloud-based media management platform. Cloudinary API keys can be used to upload, manage, and deliver media assets."+}diff --git a/pkg/detectors/cloudinary/cloudinary_integration_test.go b/pkg/detectors/cloudinary/cloudinary_integration_test.gonew file mode 100644index 000000000..04d2b0c72--- /dev/null+++ b/pkg/detectors/cloudinary/cloudinary_integration_test.go@@ -0,0 +1,168 @@+//go:build detectors+// +build detectors++package cloudinary++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 TestCloudinary_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)+ }+ cloudName := testSecrets.MustGetField("CLOUDINARY_CLOUD_NAME")+ apiKey := testSecrets.MustGetField("CLOUDINARY_API_KEY")+ apiSecret := testSecrets.MustGetField("CLOUDINARY_SECRET_KEY")+ inactiveSecret := testSecrets.MustGetField("CLOUDINARY_INACTIVE_SECRET_KEY")++ 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: fmt.Appendf([]byte{}, "You can find a Cloudinary apiSecret %s, Cloudinary apiKey %v and Cloudinary cloudName %v", apiSecret, apiKey, cloudName),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Cloudinary,+ Verified: true,+ Raw: []byte(apiKey),+ RawV2: []byte(fmt.Sprintf("%s:%s:%s", cloudName, apiKey, apiSecret)),+ },+ },+ wantErr: false,+ },+ {+ name: "found, real secrets, verification error due to timeout",+ s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)},+ args: args{+ ctx: context.Background(),+ data: fmt.Appendf([]byte{}, "You can find a Cloudinary apiSecret %s, Cloudinary apiKey %v and Cloudinary cloudName %v", apiSecret, apiKey, cloudName),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Cloudinary,+ Verified: false,+ Raw: []byte(apiKey),+ RawV2: []byte(fmt.Sprintf("%s:%s:%s", cloudName, apiKey, apiSecret)),+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },+ {+ name: "found, real secrets, verification error due to unexpected api surface",+ s: Scanner{client: common.ConstantResponseHttpClient(500, "{}")},+ args: args{+ ctx: context.Background(),+ data: fmt.Appendf([]byte{}, "You can find a Cloudinary apiSecret %s, Cloudinary apiKey %v and Cloudinary cloudName %v", apiSecret, apiKey, cloudName),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Cloudinary,+ Verified: false,+ Raw: []byte(apiKey),+ RawV2: []byte(fmt.Sprintf("%s:%s:%s", cloudName, apiKey, apiSecret)),+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },+ {+ name: "found, unverified",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: fmt.Appendf([]byte{}, "You can find a Cloudinary inactiveapiSecret %s, Cloudinary apiKey %v and Cloudinary cloudName %v", inactiveSecret, apiKey, cloudName),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Cloudinary,+ Verified: false,+ Raw: []byte(apiKey),+ RawV2: []byte(fmt.Sprintf("%s:%s:%s", cloudName, apiKey, inactiveSecret)),+ },+ },+ 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) {+ got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)+ if (err != nil) != tt.wantErr {+ t.Errorf("Cloudinary.FromData() error = %v, wantErr %v", err, tt.wantErr)+ return+ }+ for i := range got {+ if len(got[i].Raw) == 0 {+ t.Fatal("no raw secret present")+ }+ if (got[i].VerificationError() != nil) != tt.wantVerificationErr {+ t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())+ }+ }+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "ExtraData", "verificationError", "primarySecret", "SecretParts")+ if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {+ t.Errorf("Cloudinary.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/cloudinary/cloudinary_test.go b/pkg/detectors/cloudinary/cloudinary_test.gonew file mode 100644index 000000000..7f3f2a828--- /dev/null+++ b/pkg/detectors/cloudinary/cloudinary_test.go@@ -0,0 +1,151 @@+package cloudinary++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 TestCloudinary_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})++ tests := []struct {+ name string+ input string+ want []string+ }{+ {+ name: "valid pattern",+ input: `+ [INFO] Sending request to the API+ [DEBUG] Using cloudinary_apiSecret=ndiawudh1_wdajwoidjajawdeps+ [DEBUG] Using cloudinary_apiKey=218873249723411+ [DEBUG] Using cloudinary_cloudName=wdjaiwojd+ [INFO] Response received: 200 OK+ `,+ want: []string{"wdjaiwojd" + ":" + "218873249723411" + ":" + "ndiawudh1_wdajwoidjajawdeps"},+ },+ {+ name: "valid pattern - cloudinary api environment variable",+ input: `+ [INFO] Sending request to the cloudinary+ [DEBUG] Using url=cloudinary://715268876851676:V-fwwRhcp3VrRPAqaFkLq3rpa60@fakwfpoaj+ [INFO] Response received: 200 OK+ `,+ want: []string{"fakwfpoaj" + ":" + "715268876851676" + ":" + "V-fwwRhcp3VrRPAqaFkLq3rpa60"},+ },++ {+ name: "valid pattern - out of prefix range - apikey",+ input: `+ [INFO] Sending request to the cloudinary+ [DEBUG] Using cloudName=wdjaiwojd+ [DEBUG] Using cloudinary_apiSecret=ndiawudh1_wdajwoidjajawdeps+ [DEBUG] apiKey=218873249723411+ [INFO] Response received: 200 OK+ `,+ want: nil,+ },+ {+ name: "valid pattern - out of prefix range - apiSecret",+ input: `+ [INFO] Sending request to the cloudinary+ [DEBUG] Using cloudName=wdjaiwojd+ [DEBUG] apiKey=218873249723411+ [DEBUG] Using apiSecret=ndiawudh1_wdajwoidjajawdeps+ [INFO] Response received: 200 OK+ `,+ want: nil,+ },+ {+ name: "valid pattern - out of prefix range - cloudName",+ input: `+ [INFO] Sending request to the cloudinary+ [DEBUG] apiKey=218873249723411+ [DEBUG] Using apiSecret=ndiawudh1_wdajwoidjajawdeps+ [INFO] Response received: 200 OK+ [DEBUG] Used cloudName=wdjaiwojd+ `,+ want: nil,+ },+ {+ name: "valid pattern - only apikey",+ input: `+ [INFO] Sending request to the cloudinary API+ [DEBUG] Using apiKey=218873249723411+ `,+ want: nil,+ },+ {+ name: "valid pattern - only secret",+ input: `+ [INFO] Sending request to the cloudinary API+ [DEBUG] Using apiSecret=ndiawudh1_wdajwoidjajawdeps+ [INFO] Response received: 200 OK+ `,+ want: nil,+ },+ {+ name: "valid pattern - only cloudName",+ input: `+ [INFO] Sending request to the cloudinary API+ [DEBUG] Using cloudName=wdjaiwojd+ [INFO] Response received: 200 OK+ `,+ want: nil,+ },+ {+ name: "invalid pattern - invalid api key length",+ input: `+ [INFO] Sending request to the cloudinary API+ [DEBUG] Using apikey=12312312432541444+ [DEBUG] Using apiSecret=ndiawudh1_wdajwoidjajawdeps+ [DEBUG] Using cloudName=wdjaiwojd+ [ERROR] Response received: 400 BadRequest+ `,+ 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)+ }+ })+ }+}diff --git a/pkg/engine/defaults/defaults.go b/pkg/engine/defaults/defaults.goindex f769af2c5..46db6f158 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -165,6 +165,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudflarecakey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudflareglobalapikey""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudimage"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudinary""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudmersive""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudplan""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/cloudsmith"@@ -1037,6 +1038,7 @@ func buildDetectorList() []detectors.Detector {&cloudflarecakey.Scanner{},&cloudflareglobalapikey.Scanner{},&cloudimage.Scanner{},+ &cloudinary.Scanner{},&cloudmersive.Scanner{},&cloudplan.Scanner{},&cloudsmith.Scanner{},diff --git a/pkg/pb/detector_typepb/detector_type.pb.go b/pkg/pb/detector_typepb/detector_type.pb.goindex 51f668528..9876452be 100644--- a/pkg/pb/detector_typepb/detector_type.pb.go+++ b/pkg/pb/detector_typepb/detector_type.pb.go@@ -1101,6 +1101,7 @@ const (DetectorType_BitbucketDataCenter DetectorType = 1045DetectorType_JiraDataCenterPAT DetectorType = 1046DetectorType_ConfluenceDataCenter DetectorType = 1047+ DetectorType_Cloudinary DetectorType = 1048)// Enum value maps for DetectorType.@@ -2150,6 +2151,7 @@ var (1045: "BitbucketDataCenter",1046: "JiraDataCenterPAT",1047: "ConfluenceDataCenter",+ 1048: "Cloudinary",}DetectorType_value = map[string]int32{"Alibaba": 0,@@ -3196,6 +3198,7 @@ var ("BitbucketDataCenter": 1045,"JiraDataCenterPAT": 1046,"ConfluenceDataCenter": 1047,+ "Cloudinary": 1048,})@@ -3231,7 +3234,7 @@ var File_detector_type_proto protoreflect.FileDescriptorvar file_detector_type_proto_rawDesc = []byte{0x0a, 0x13, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x2e,0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x5f,- 0x74, 0x79, 0x70, 0x65, 0x2a, 0x8c, 0x88, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74,+ 0x74, 0x79, 0x70, 0x65, 0x2a, 0x9d, 0x88, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74,0x6f, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x41, 0x6c, 0x69, 0x62, 0x61, 0x62,0x61, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x41, 0x4d, 0x51, 0x50, 0x10, 0x01, 0x12, 0x07, 0x0a,0x03, 0x41, 0x57, 0x53, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x7a, 0x75, 0x72, 0x65, 0x10,@@ -4320,11 +4323,12 @@ var file_detector_type_proto_rawDesc = []byte{0x08, 0x12, 0x16, 0x0a, 0x11, 0x4a, 0x69, 0x72, 0x61, 0x44, 0x61, 0x74, 0x61, 0x43, 0x65, 0x6e,0x74, 0x65, 0x72, 0x50, 0x41, 0x54, 0x10, 0x96, 0x08, 0x12, 0x19, 0x0a, 0x14, 0x43, 0x6f, 0x6e,0x66, 0x6c, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x44, 0x61, 0x74, 0x61, 0x43, 0x65, 0x6e, 0x74, 0x65,- 0x72, 0x10, 0x97, 0x08, 0x42, 0x41, 0x5a, 0x3f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,- 0x6f, 0x6d, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69,- 0x74, 0x79, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x68, 0x6f, 0x67, 0x2f, 0x76, 0x33,- 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x62, 0x2f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72,- 0x5f, 0x74, 0x79, 0x70, 0x65, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x72, 0x10, 0x97, 0x08, 0x12, 0x0f, 0x0a, 0x0a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x69, 0x6e, 0x61,+ 0x72, 0x79, 0x10, 0x98, 0x08, 0x42, 0x41, 0x5a, 0x3f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,+ 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x73, 0x65, 0x63, 0x75, 0x72,+ 0x69, 0x74, 0x79, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x68, 0x6f, 0x67, 0x2f, 0x76,+ 0x33, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x62, 0x2f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f,+ 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (diff --git a/proto/detector_type.proto b/proto/detector_type.protoindex ddd4c83c6..5b0f0f42f 100644--- a/proto/detector_type.proto+++ b/proto/detector_type.proto@@ -1049,4 +1049,5 @@ enum DetectorType {BitbucketDataCenter = 1045;JiraDataCenterPAT = 1046;ConfluenceDataCenter = 1047;+ Cloudinary = 1048;}