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
104 changes: 104 additions & 0 deletions pkg/detectors/perplexity/perplexity.go
Original file line number Diff line number Diff line change
@@ -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."
}
108 changes: 108 additions & 0 deletions pkg/detectors/perplexity/perplexity_integration_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
170 changes: 170 additions & 0 deletions pkg/detectors/perplexity/perplexity_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading