diff --git a/pkg/detectors/perplexity/perplexity.go b/pkg/detectors/perplexity/perplexity.go new file mode 100644 index 000000000000..5666c7b0fefe --- /dev/null +++ b/pkg/detectors/perplexity/perplexity.go @@ -0,0 +1,104 @@ +package perplexity + +import ( + "context" + "fmt" + "io" + "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 +} + +// Ensure the Scanner satisfies the interface at compile time. +var _ detectors.Detector = (*Scanner)(nil) + +var ( + defaultClient = common.SaneHttpClient() + keyPat = regexp.MustCompile(`\b(pplx-[a-zA-Z0-9]{48})\b`) +) + +func (s Scanner) Keywords() []string { + return []string{"pplx-"} +} + +// FromData will find and optionally verify Perplexity API keys 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_Perplexity, + Raw: []byte(match), + ExtraData: map[string]string{ + "rotation_guide": "https://docs.perplexity.ai/docs/admin/api-key-management", + }, + SecretParts: map[string]string{"key": match}, + } + + if verify { + client := s.client + if client == nil { + client = defaultClient + } + + isVerified, extraData, verificationErr := verifyMatch(ctx, client, match) + s1.Verified = isVerified + for k, v := range extraData { + s1.ExtraData[k] = v + } + s1.SetVerificationError(verificationErr, match) + } + + results = append(results, s1) + } + + return +} + +func verifyMatch(ctx context.Context, client *http.Client, token string) (bool, map[string]string, error) { + // The read-only List Models endpoint returns 200 OK for valid keys and 401 Unauthorized for invalid ones. + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.perplexity.ai/v1/models", nil) + if err != nil { + return false, nil, err + } + req.Header.Add("Authorization", "Bearer "+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: + return true, nil, nil + case http.StatusUnauthorized: + 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_Perplexity +} + +func (s Scanner) Description() string { + return "Perplexity provides search and model inference APIs. Perplexity API keys grant access to paid search, agent and model endpoints billed to the key owner's account." +} diff --git a/pkg/detectors/perplexity/perplexity_integration_test.go b/pkg/detectors/perplexity/perplexity_integration_test.go new file mode 100644 index 000000000000..284cfa96c4bb --- /dev/null +++ b/pkg/detectors/perplexity/perplexity_integration_test.go @@ -0,0 +1,108 @@ +//go:build detectors +// +build detectors + +package perplexity + +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 TestPerplexity_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("PERPLEXITY") + inactiveSecret := testSecrets.MustGetField("PERPLEXITY_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 perplexity secret %s within", secret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_Perplexity, + Verified: true, + }, + }, + wantErr: false, + wantVerificationErr: false, + }, + { + name: "found, unverified", + s: Scanner{}, + args: args{ + ctx: context.Background(), + data: []byte(fmt.Sprintf("You can find a perplexity secret %s within", inactiveSecret)), + verify: true, + }, + want: []detectors.Result{ + { + DetectorType: detector_typepb.DetectorType_Perplexity, + Verified: false, + }, + }, + wantErr: false, + wantVerificationErr: 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, + wantVerificationErr: 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("Scanner.FromData() error = %v, wantErr %v", err, tt.wantErr) + return + } + for i := range got { + if (got[i].VerificationError() != nil) != tt.wantVerificationErr { + t.Errorf("Scanner.FromData() verification error = %v, wantVerificationErr %v", got[i].VerificationError(), tt.wantVerificationErr) + } + } + opts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "ExtraData", "SecretParts", "verificationError") + if diff := cmp.Diff(got, tt.want, opts, cmpopts.IgnoreUnexported(detectors.Result{})); diff != "" { + t.Errorf("Scanner.FromData() %s diff: (-got +want)\n%s", tt.name, diff) + } + }) + } +} diff --git a/pkg/detectors/perplexity/perplexity_test.go b/pkg/detectors/perplexity/perplexity_test.go new file mode 100644 index 000000000000..d85da968fb70 --- /dev/null +++ b/pkg/detectors/perplexity/perplexity_test.go @@ -0,0 +1,170 @@ +package perplexity + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + + "github.com/trufflesecurity/trufflehog/v3/pkg/common" + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" + "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick" +) + +// Test keys are assembled at runtime so the source never contains a literal +// that secret scanners would flag as a Perplexity key. +var ( + testKey1 = "pplx-" + strings.Repeat("u8jzPde0", 6) + testKey2 = "pplx-" + strings.Repeat("IhKtJ0Rl", 6) + testKey3 = "pplx-" + strings.Repeat("CsMehGAk", 6) +) + +func TestPerplexity_Pattern(t *testing.T) { + d := Scanner{} + ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d}) + tests := []struct { + name string + input string + want []string + }{ + { + name: "typical pattern", + input: "perplexity_api_key = '" + testKey1 + "'", + want: []string{testKey1}, + }, + { + name: "pattern inside json", + input: `{"PERPLEXITY_API_KEY": "` + testKey2 + `" }`, + want: []string{testKey2}, + }, + { + name: "too short", + input: "PERPLEXITY_API_KEY=pplx-1234567890abcdef", + want: nil, + }, + { + name: "too long", + input: "PERPLEXITY_API_KEY=" + testKey1 + "X", + want: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + detectorMatches := ahoCorasickCore.FindDetectorMatches([]byte(test.input)) + if len(detectorMatches) == 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 TestPerplexity_VerifyMatch(t *testing.T) { + token := testKey3 + errTransport := errors.New("transport failure") + + tests := []struct { + name string + responseCode int + transportErr error + wantVerified bool + wantErr string + }{ + {name: "200 OK - verified", responseCode: http.StatusOK, wantVerified: true}, + {name: "401 Unauthorized - unverified", responseCode: http.StatusUnauthorized}, + {name: "403 Forbidden - verification error", responseCode: http.StatusForbidden, wantErr: "unexpected HTTP response status 403"}, + {name: "429 Too Many Requests - verification error", responseCode: http.StatusTooManyRequests, wantErr: "unexpected HTTP response status 429"}, + {name: "500 Internal Server Error - verification error", responseCode: http.StatusInternalServerError, wantErr: "unexpected HTTP response status 500"}, + {name: "transport failure - verification error", transportErr: errTransport, wantErr: errTransport.Error()}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := Scanner{client: &http.Client{Transport: common.FakeTransport{ + CreateResponse: func(req *http.Request) (*http.Response, error) { + if req.Method != http.MethodGet { + t.Errorf("method = %s, want GET", req.Method) + } + if got := req.URL.String(); got != "https://api.perplexity.ai/v1/models" { + t.Errorf("url = %s", got) + } + if got := req.Header.Get("Authorization"); got != "Bearer "+token { + t.Errorf("Authorization = %q", got) + } + if tt.transportErr != nil { + return nil, tt.transportErr + } + return &http.Response{ + Request: req, + StatusCode: tt.responseCode, + Body: io.NopCloser(strings.NewReader("{}")), + }, nil + }, + }}} + + results, err := s.FromData(context.Background(), true, []byte("PERPLEXITY_API_KEY="+token)) + if err != nil { + t.Fatalf("FromData error = %v", err) + } + if len(results) != 1 { + t.Fatalf("got %d results, want 1", len(results)) + } + r := results[0] + + if r.Verified != tt.wantVerified { + t.Errorf("Verified = %v, want %v", r.Verified, tt.wantVerified) + } + verificationErr := r.VerificationError() + if tt.wantErr == "" { + if verificationErr != nil { + t.Errorf("unexpected verification error: %v", verificationErr) + } + } else if verificationErr == nil || !strings.Contains(verificationErr.Error(), tt.wantErr) { + t.Errorf("verification error = %v, want it to contain %q", verificationErr, tt.wantErr) + } + if got := r.ExtraData["rotation_guide"]; got != "https://docs.perplexity.ai/docs/admin/api-key-management" { + t.Errorf("rotation_guide = %q", got) + } + if got := r.SecretParts["key"]; got != token { + t.Errorf("SecretParts[key] = %q, want %q", got, token) + } + }) + } +} diff --git a/pkg/engine/defaults/defaults.go b/pkg/engine/defaults/defaults.go index 95f1c41032ba..3a3e0a4a596c 100644 --- a/pkg/engine/defaults/defaults.go +++ b/pkg/engine/defaults/defaults.go @@ -587,6 +587,7 @@ import ( "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/peopledatalabs" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/pepipost" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/percy" + "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/perplexity" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/pganalyzereadkey" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/photoroom" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/phraseaccesstoken" @@ -1518,6 +1519,7 @@ func buildDetectorList() []detectors.Detector { &peopledatalabs.Scanner{}, &pepipost.Scanner{}, &percy.Scanner{}, + &perplexity.Scanner{}, &pganalyzereadkey.Scanner{}, &photoroom.Scanner{}, &phraseaccesstoken.Scanner{}, diff --git a/pkg/pb/detector_typepb/detector_type.pb.go b/pkg/pb/detector_typepb/detector_type.pb.go index dd4728afab77..1f53907c19ee 100644 --- a/pkg/pb/detector_typepb/detector_type.pb.go +++ b/pkg/pb/detector_typepb/detector_type.pb.go @@ -1135,6 +1135,7 @@ const ( DetectorType_Composio DetectorType = 1077 DetectorType_Serval DetectorType = 1078 DetectorType_Baseten DetectorType = 1079 + DetectorType_Perplexity DetectorType = 1080 ) // Enum value maps for DetectorType. @@ -2216,6 +2217,7 @@ var ( 1077: "Composio", 1078: "Serval", 1079: "Baseten", + 1080: "Perplexity", } DetectorType_value = map[string]int32{ "Alibaba": 0, @@ -3294,6 +3296,7 @@ var ( "Composio": 1077, "Serval": 1078, "Baseten": 1079, + "Perplexity": 1080, } ) @@ -3329,7 +3332,7 @@ var File_detector_type_proto protoreflect.FileDescriptor var 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, 0x92, 0x8d, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74, + 0x74, 0x79, 0x70, 0x65, 0x2a, 0xa3, 0x8d, 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, @@ -4458,12 +4461,13 @@ var file_detector_type_proto_rawDesc = []byte{ 0x12, 0x0e, 0x0a, 0x09, 0x46, 0x69, 0x72, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x10, 0xb4, 0x08, 0x12, 0x0d, 0x0a, 0x08, 0x43, 0x6f, 0x6d, 0x70, 0x6f, 0x73, 0x69, 0x6f, 0x10, 0xb5, 0x08, 0x12, 0x0b, 0x0a, 0x06, 0x53, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x10, 0xb6, 0x08, 0x12, 0x0c, 0x0a, 0x07, - 0x42, 0x61, 0x73, 0x65, 0x74, 0x65, 0x6e, 0x10, 0xb7, 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, + 0x42, 0x61, 0x73, 0x65, 0x74, 0x65, 0x6e, 0x10, 0xb7, 0x08, 0x12, 0x0f, 0x0a, 0x0a, 0x50, 0x65, + 0x72, 0x70, 0x6c, 0x65, 0x78, 0x69, 0x74, 0x79, 0x10, 0xb8, 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.proto index b79ee4128d84..235788bd5dce 100644 --- a/proto/detector_type.proto +++ b/proto/detector_type.proto @@ -1081,4 +1081,5 @@ enum DetectorType { Composio = 1077; Serval = 1078; Baseten = 1079; + Perplexity = 1080; }