Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
feat(detectors): add Composio API key detector (#5322)
Saransh Rana7dba289971f8
diff --git a/main.go b/main.goindex 3cc3fe9e8..dee314398 100644--- a/main.go+++ b/main.go@@ -601,6 +601,7 @@ func run(state overseer.State, logSync func() error) {feature.MSTeamsWebhookV2DetectorEnabled.Store(true)feature.SolarwindsDetectorEnabled.Store(true)feature.ResendDetectorEnabled.Store(true)+ feature.ComposioDetectorEnabled.Store(true)feature.WeightsAndBiasesV2DetectorEnabled.Store(true)feature.HumioAPITokenDetectorEnabled.Store(true)feature.KongKonnectDetectorEnabled.Store(true)diff --git a/pkg/detectors/composio/composio.go b/pkg/detectors/composio/composio.gonew file mode 100644index 000000000..220b5ae6d--- /dev/null+++ b/pkg/detectors/composio/composio.go@@ -0,0 +1,269 @@+package composio++import (+ "cmp"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"++ 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+}++// Ensure the Scanner satisfies the interfaces at compile time.+var _ detectors.Detector = (*Scanner)(nil)+var _ detectors.EndpointCustomizer = (*Scanner)(nil)+var _ detectors.CloudProvider = (*Scanner)(nil)++func (Scanner) CloudEndpoint() string { return "https://backend.composio.dev" }++var defaultClient = common.SaneHttpClient()++// getClient returns the client verification requests go through. The+// VerificationClient wrap is what attaches the operator's access token when+// --verifier points at an auth-protected endpoint; without it those requests+// go out unauthenticated and every key comes back looking dead.+func (s Scanner) getClient() *http.Client {+ return s.VerificationClient(cmp.Or(s.client, defaultClient))+}++const rotationGuide = "https://docs.composio.dev/reference/api-reference/api-keys/postApiKeyRevocation"++// maxErrorBodyBytes bounds how much of an error response is read. Composio's+// error envelope is a few hundred bytes; anything larger is not one.+const maxErrorBodyBytes = 64 * 1024++// Composio issues three key types, all a fixed prefix followed by URL-safe+// nanoid characters. oak_ and uak_ contain "ak_", so every pattern requires a+// non-alphabet character (or start of input) before the prefix. The trailing+// boundary is checked in code rather than in the pattern: a consuming trailing+// group would swallow the single delimiter between two adjacent keys and drop+// the second one.+//+// Each key type authenticates through its own header and its own routes. A key+// sent under another type's header is answered with the same 401 as no header+// at all, so verification cannot share one endpoint across types: every type+// carries the cheapest read-only route it can authenticate.+type keyPattern struct {+ keyType string+ re *regexp.Regexp+ verifyPath string+ header string+}++var keyPatterns = []keyPattern{+ {+ keyType: "project",+ re: regexp.MustCompile(`(?:^|[^A-Za-z0-9_-])(ak_[A-Za-z0-9_-]{20})`),+ verifyPath: "/api/v3/toolkits/categories",+ header: "x-api-key",+ },+ {+ keyType: "org",+ re: regexp.MustCompile(`(?:^|[^A-Za-z0-9_-])(oak_[A-Za-z0-9_-]{20})`),+ verifyPath: "/api/v3/org/owner/project/list",+ header: "x-org-api-key",+ },+ {+ keyType: "user",+ re: regexp.MustCompile(`(?:^|[^A-Za-z0-9_-])(uak_[A-Za-z0-9_-]{43})`),+ verifyPath: "/api/v3/org/list?limit=1",+ header: "x-user-api-key",+ },+}++// isKeyAlphabet reports whether b can appear inside a Composio key.+func isKeyAlphabet(b byte) bool {+ return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '_' || b == '-'+}++// endsAtBoundary reports whether the key ending at end is followed by end of+// input or a character that cannot be part of a key.+func endsAtBoundary(data string, end int) bool {+ return end >= len(data) || !isKeyAlphabet(data[end])+}++// Keywords are used for efficiently pre-filtering chunks. "ak_" is a substring+// of all three prefixes.+func (s Scanner) Keywords() []string {+ return []string{"ak_"}+}++// FromData finds Composio API keys in a given set of bytes and, when asked,+// verifies each one against the Composio API.+func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {+ dataStr := string(data)++ seen := make(map[string]struct{})+ for _, pattern := range keyPatterns {+ for _, loc := range pattern.re.FindAllStringSubmatchIndex(dataStr, -1) {+ start, end := loc[2], loc[3]+ if !endsAtBoundary(dataStr, end) {+ continue+ }+ token := dataStr[start:end]+ if _, dup := seen[token]; dup {+ continue+ }+ seen[token] = struct{}{}++ r := detectors.Result{+ DetectorType: detector_typepb.DetectorType_Composio,+ Raw: []byte(token),+ SecretParts: map[string]string{"key": token},+ ExtraData: map[string]string{+ "key_type": pattern.keyType,+ "rotation_guide": rotationGuide,+ },+ }++ if verify {+ client := s.getClient()++ // Only the cloud endpoint and operator-configured endpoints are+ // used; URLs found in scanned data are never called. Only+ // non-nil errors overwrite lastErr so a clean 401 from one+ // endpoint does not erase a transient failure from another.+ var lastErr error+ for _, baseURL := range s.Endpoints() {+ verified, extra, vErr := verifyMatch(ctx, client, baseURL, pattern, token)+ r.Verified = verified+ if vErr != nil {+ lastErr = vErr+ }+ if verified {+ lastErr = nil+ r.ExtraData["endpoint"] = baseURL+ for k, v := range extra {+ r.ExtraData[k] = v+ }+ break+ }+ }+ r.SetVerificationError(lastErr, token)+ }++ results = append(results, r)+ }+ }++ return results, nil+}++// apiError is the envelope every Composio API error carries. The slug is+// stable across releases; the message is human copy.+type apiError struct {+ Error struct {+ Message string `json:"message"`+ Slug string `json:"slug"`+ Code int `json:"code"`+ } `json:"error"`+}++// verifyMatch sends the key on the route its type can authenticate and maps+// the answer to verified, dead, or undecided. Composio deliberately answers+// several unrelated conditions with 401, so the verdict comes from the error+// slug in the body, never from the status code alone:+//+// - 200: live.+// - 401 APIKey_InvalidAPIKey, APIKey_APIKeyExpired, UserApiKey_Unauthorized,+// and HTTP_Unauthorized "Invalid x-org-api-key": the hash matched no live+// row. Dead, no error.+// - 401 Auth_Unauthorized naming the key's IP allowlist: the key exists and+// works from allowlisted addresses. Live, reported with the restriction.+// - 403 carrying the envelope: Composio only refuses with 403 after the+// credential resolved (a scoped key without the route's permission, an+// org-level restriction). Live, reported with the restriction.+// - Anything else (a banned scanner address answers "Access denied", a+// stripped header answers Auth_NoAuthProvided, a WAF page has no+// envelope, 429, 5xx): undecided, surfaced as a verification error.+//+// The org key's dead slug HTTP_Unauthorized is shared with the banned-address+// answer, so that one branch also reads the message; a copy change there+// degrades to an undecided error, never to a wrong verdict.+func verifyMatch(+ ctx context.Context,+ client *http.Client,+ baseURL string,+ pattern keyPattern,+ token string,+) (bool, map[string]string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+pattern.verifyPath, nil)+ if err != nil {+ return false, nil, err+ }+ req.Header.Set(pattern.header, token)+ req.Header.Set("Accept", "application/json")++ 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, http.StatusForbidden:+ var body apiError+ dec := json.NewDecoder(io.LimitReader(res.Body, maxErrorBodyBytes))+ if err := dec.Decode(&body); err != nil || body.Error.Slug == "" {+ return false, nil, fmt.Errorf("HTTP %d without a Composio error envelope", res.StatusCode)+ }+ return classifyRejection(res.StatusCode, body)++ default:+ return false, nil, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)+ }+}++func classifyRejection(status int, body apiError) (bool, map[string]string, error) {+ slug, message := body.Error.Slug, body.Error.Message++ switch {+ case status == http.StatusUnauthorized && (slug == "APIKey_InvalidAPIKey" ||+ slug == "APIKey_APIKeyExpired" || slug == "UserApiKey_Unauthorized"):+ return false, nil, nil++ case status == http.StatusUnauthorized && slug == "HTTP_Unauthorized" &&+ strings.HasPrefix(message, "Invalid x-org-api-key"):+ return false, nil, nil++ case status == http.StatusUnauthorized && slug == "Auth_Unauthorized" && strings.Contains(message, "IP allowlist"):+ return true, map[string]string{"restriction": "ip_allowlist"}, nil++ case status == http.StatusForbidden && slug == "APIKey_InsufficientPermissions":+ return true, map[string]string{"restriction": "insufficient_permissions"}, nil++ case status == http.StatusForbidden:+ return true, map[string]string{"restriction": slug}, nil++ default:+ return false, nil, fmt.Errorf("HTTP %d %s did not judge the key: %s", status, slug, message)+ }+}++func (s Scanner) Type() detector_typepb.DetectorType {+ return detector_typepb.DetectorType_Composio+}++func (s Scanner) Description() string {+ return "Composio is an integration platform for AI agents. Composio API " ++ "keys authenticate calls that execute tools, read connected accounts " ++ "and manage triggers for a project, an organization or a user."+}diff --git a/pkg/detectors/composio/composio_integration_test.go b/pkg/detectors/composio/composio_integration_test.gonew file mode 100644index 000000000..99e3b21d3--- /dev/null+++ b/pkg/detectors/composio/composio_integration_test.go@@ -0,0 +1,179 @@+//go:build detectors+// +build detectors++package composio++import (+ "context"+ "fmt"+ "net/http"+ "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"+)++// newTestScanner mirrors what DefaultDetectors() does at startup: without the+// cloud endpoint, Endpoints() is empty and verification never runs.+func newTestScanner(client *http.Client) Scanner {+ s := Scanner{client: client}+ s.SetCloudEndpoint((Scanner{}).CloudEndpoint())+ s.UseCloudEndpoint(true)+ return s+}++func TestComposio_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("COMPOSIO_PROJECT_KEY")+ inactiveSecret := testSecrets.MustGetField("COMPOSIO_PROJECT_KEY_INACTIVE")++ unverifiedExtra := map[string]string{+ "key_type": "project",+ "rotation_guide": rotationGuide,+ }+ verifiedExtra := map[string]string{+ "key_type": "project",+ "rotation_guide": rotationGuide,+ "endpoint": (Scanner{}).CloudEndpoint(),+ }++ 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: newTestScanner(nil),+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("COMPOSIO_API_KEY=%s", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Composio,+ Verified: true,+ ExtraData: verifiedExtra,+ },+ },+ },+ {+ name: "found, unverified",+ s: newTestScanner(nil),+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("COMPOSIO_API_KEY=%s", inactiveSecret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Composio,+ Verified: false,+ ExtraData: unverifiedExtra,+ },+ },+ },+ {+ name: "not found",+ s: newTestScanner(nil),+ args: args{+ ctx: context.Background(),+ data: []byte("You cannot find the secret within"),+ verify: true,+ },+ want: nil,+ },+ {+ name: "found, would be verified if not for timeout",+ s: newTestScanner(common.SaneHttpClientTimeOut(1 * time.Microsecond)),+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("COMPOSIO_API_KEY=%s", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Composio,+ Verified: false,+ ExtraData: unverifiedExtra,+ },+ },+ wantVerificationErr: true,+ },+ {+ name: "found, verified but unexpected api surface",+ s: newTestScanner(common.ConstantResponseHttpClient(404, "")),+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("COMPOSIO_API_KEY=%s", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Composio,+ Verified: false,+ ExtraData: unverifiedExtra,+ },+ },+ 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("Composio.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.Errorf("Composio.FromData() error = %v, wantVerificationErr %v",+ got[i].VerificationError(), tt.wantVerificationErr)+ }+ }+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "verificationError", "SecretParts")+ ignoreUnexported := cmpopts.IgnoreUnexported(detectors.Result{})+ if diff := cmp.Diff(got, tt.want, ignoreOpts, ignoreUnexported); diff != "" {+ t.Errorf("Composio.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/composio/composio_test.go b/pkg/detectors/composio/composio_test.gonew file mode 100644index 000000000..37072d720--- /dev/null+++ b/pkg/detectors/composio/composio_test.go@@ -0,0 +1,104 @@+package composio++import (+ "context"+ "fmt"+ "testing"++ "github.com/google/go-cmp/cmp"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"+)++// Synthetic vectors from Composio's published format spec; none were ever minted.+const (+ projectKey = "ak_jI60uPF6adMkCuBFESjq"+ projectKeyDashEnd = "ak_Qbez9ytnft9XyXAGPL0-"+ orgKey = "oak_iuGvTZ4eiiy3umBWjwTt"+ userKey = "uak_TRFvy_o-mFznI3IyljByM5LL-SudKFv47vULpKuK2ai"+)++func TestComposio_Pattern(t *testing.T) {+ d := Scanner{}+ ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})+ tests := []struct {+ name string+ input string+ want []string+ }{+ {name: "project key", input: fmt.Sprintf("COMPOSIO_API_KEY=%s", projectKey), want: []string{projectKey}},+ {+ name: "project key ending in dash",+ input: fmt.Sprintf("key: '%s'", projectKeyDashEnd),+ want: []string{projectKeyDashEnd},+ },+ {+ name: "org key is reported once, not also as a project key",+ input: fmt.Sprintf("COMPOSIO_ORG_KEY=%s", orgKey),+ want: []string{orgKey},+ },+ {+ name: "user key is reported once, not also as a project key",+ input: fmt.Sprintf("x-user-api-key: %s", userKey),+ want: []string{userKey},+ },+ {name: "duplicates collapse", input: fmt.Sprintf("%s %s", projectKey, projectKey), want: []string{projectKey}},+ {+ name: "two keys separated by a single comma are both reported",+ input: fmt.Sprintf("%s,%s", projectKey, projectKeyDashEnd),+ want: []string{projectKey, projectKeyDashEnd},+ },+ {+ name: "key glued to a following alphabet character is not a key",+ input: fmt.Sprintf("%sZ", projectKey),+ want: []string{},+ },+ {name: "wrong length", input: "COMPOSIO_API_KEY=ak_jI60uPF6adMkCuBFESj", want: []string{}},+ {name: "placeholder", input: "COMPOSIO_API_KEY=ak_test", want: []string{}},+ }++ 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) {+ t.Errorf("expected %d results, received %d", len(test.want), len(results))+ return+ }++ actual := make(map[string]struct{}, len(results))+ for _, r := range results {+ 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 TestComposio_KeyType(t *testing.T) {+ d := Scanner{}+ results, err := d.FromData(context.Background(), false, []byte(orgKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected one result, got %d (err %v)", len(results), err)+ }+ if got := results[0].ExtraData["key_type"]; got != "org" {+ t.Errorf("key_type = %q, want org", got)+ }+}diff --git a/pkg/detectors/composio/composio_verify_test.go b/pkg/detectors/composio/composio_verify_test.gonew file mode 100644index 000000000..6c6cd1f27--- /dev/null+++ b/pkg/detectors/composio/composio_verify_test.go@@ -0,0 +1,342 @@+package composio++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth/verifierauthtest"+)++// Real production envelopes captured 2026-09-17 with never-minted keys; the+// request_id field is dropped and the masked key placeholder is synthetic.+const (+ bodyProjectInvalid = `{"error":{"message":"Invalid API key: ak_**ESjq","code":801,"slug":"APIKey_InvalidAPIKey","status":401}}`+ bodyProjectExpired = `{"error":{"message":"API key has expired","code":811,"slug":"APIKey_APIKeyExpired","status":401}}`+ bodyOrgInvalid = `{"error":{"message":"Invalid x-org-api-key. Please check you are using a valid API key.","code":10401,"slug":"HTTP_Unauthorized","status":401}}`+ bodyUserInvalid = `{"error":{"message":"Invalid or revoked user API key","code":2113,"slug":"UserApiKey_Unauthorized","status":401}}`+ bodyNoAuth = `{"error":{"message":"No API key provided","code":906,"slug":"Auth_NoAuthProvided","status":401}}`+ bodyIPAllowlist = `{"error":{"message":"This request comes from IP address 203.0.113.9, which is not in this API key’s IP allowlist. Requests using this key are only accepted from explicitly allowlisted IP addresses.","code":902,"slug":"Auth_Unauthorized","status":401}}`+ bodyAccessDenied = `{"error":{"message":"Access denied","code":902,"slug":"Auth_Unauthorized","status":401}}`+ bodyOrgAccessDenied = `{"error":{"message":"Access denied","code":10401,"slug":"HTTP_Unauthorized","status":401}}`+ bodyNoPermission = `{"error":{"message":"This API key does not have read access to toolkits","code":812,"slug":"APIKey_InsufficientPermissions","status":403}}`+ bodyForbiddenUnknown = `{"error":{"message":"Organization is suspended","code":2206,"slug":"Organization_InsufficientPermissions","status":403}}`+ bodyHTMLChallenge = `<!DOCTYPE html><html><head><title>Just a moment...</title></head></html>`+ bodyRateLimited = `{"error":{"message":"Too many requests","code":429,"slug":"RateLimit_Exceeded","status":429}}`+)++type capturedRequest struct {+ method string+ path string+ headers http.Header+}++// newVerifyServer answers every request with the given status and body and+// records the last request it saw.+func newVerifyServer(t *testing.T, status int, body string) (*httptest.Server, *capturedRequest, *int32) {+ t.Helper()+ captured := &capturedRequest{}+ var calls int32+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ atomic.AddInt32(&calls, 1)+ captured.method = r.Method+ captured.path = r.URL.RequestURI()+ captured.headers = r.Header.Clone()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _, _ = w.Write([]byte(body))+ }))+ t.Cleanup(ts.Close)+ return ts, captured, &calls+}++func scannerFor(ts *httptest.Server) Scanner {+ s := Scanner{}+ s.SetCloudEndpoint(ts.URL)+ s.UseCloudEndpoint(true)+ return s+}++func TestComposio_Verification_RequestShape(t *testing.T) {+ tests := []struct {+ name string+ key string+ wantPath string+ wantHeader string+ }{+ {name: "project key", key: projectKey, wantPath: "/api/v3/toolkits/categories", wantHeader: "x-api-key"},+ {name: "org key", key: orgKey, wantPath: "/api/v3/org/owner/project/list", wantHeader: "x-org-api-key"},+ {name: "user key", key: userKey, wantPath: "/api/v3/org/list?limit=1", wantHeader: "x-user-api-key"},+ }++ keyHeaders := []string{"x-api-key", "x-org-api-key", "x-user-api-key", "Authorization"}++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ ts, captured, _ := newVerifyServer(t, http.StatusOK, `{}`)+ s := scannerFor(ts)++ results, err := s.FromData(context.Background(), true, []byte("key="+tt.key))+ if err != nil {+ t.Fatalf("FromData error: %v", err)+ }+ if len(results) != 1 {+ t.Fatalf("expected 1 result, got %d", len(results))+ }+ if captured.method != http.MethodGet {+ t.Errorf("method = %s, want GET", captured.method)+ }+ if captured.path != tt.wantPath {+ t.Errorf("path = %s, want %s", captured.path, tt.wantPath)+ }+ if got := captured.headers.Get(tt.wantHeader); got != tt.key {+ t.Errorf("header %s = %q, want the key", tt.wantHeader, got)+ }+ for _, h := range keyHeaders {+ if h != tt.wantHeader && captured.headers.Get(h) != "" {+ t.Errorf("header %s must not be sent for a %s key", h, tt.name)+ }+ }+ if !results[0].Verified {+ t.Error("200 must verify the key")+ }+ if results[0].VerificationError() != nil {+ t.Errorf("unexpected verification error: %v", results[0].VerificationError())+ }+ if got := results[0].ExtraData["endpoint"]; got != ts.URL {+ t.Errorf("ExtraData endpoint = %q, want %q", got, ts.URL)+ }+ })+ }+}++func TestComposio_Verification_Outcomes(t *testing.T) {+ tests := []struct {+ name string+ key string+ status int+ body string+ wantVerified bool+ wantErr bool+ wantRestriction string+ }{+ // Definitive rejections: the key hash matched no live row.+ {name: "project: unknown or revoked", key: projectKey, status: 401, body: bodyProjectInvalid},+ {name: "project: expired", key: projectKey, status: 401, body: bodyProjectExpired},+ {name: "org: unknown or revoked", key: orgKey, status: 401, body: bodyOrgInvalid},+ {name: "user: unknown, revoked or expired", key: userKey, status: 401, body: bodyUserInvalid},++ // Live keys the route would not serve.+ {+ name: "project: IP allowlist denial is a live key",+ key: projectKey, status: 401, body: bodyIPAllowlist,+ wantVerified: true, wantRestriction: "ip_allowlist",+ },+ {+ name: "project: scoped key without permission is a live key",+ key: projectKey, status: 403, body: bodyNoPermission,+ wantVerified: true, wantRestriction: "insufficient_permissions",+ },++ // The API did not judge the key; never guess.+ {name: "project: banned scanner IP", key: projectKey, status: 401, body: bodyAccessDenied, wantErr: true},+ {name: "org: banned scanner IP", key: orgKey, status: 401, body: bodyOrgAccessDenied, wantErr: true},+ {name: "user: membership could not be resolved", key: userKey, status: 401, body: bodyAccessDenied, wantErr: true},+ {name: "header not recognised", key: projectKey, status: 401, body: bodyNoAuth, wantErr: true},+ {name: "401 without a Composio envelope", key: projectKey, status: 401, body: bodyHTMLChallenge, wantErr: true},+ {+ name: "org: 403 after the key resolved is a live key",+ key: orgKey, status: 403, body: bodyForbiddenUnknown,+ wantVerified: true, wantRestriction: "Organization_InsufficientPermissions",+ },+ {name: "403 without a Composio envelope", key: projectKey, status: 403, body: bodyHTMLChallenge, wantErr: true},+ {+ name: "rate limited",+ key: projectKey, status: 429, body: bodyRateLimited,+ wantErr: true,+ },+ {name: "server error", key: projectKey, status: 500, body: ``, wantErr: true},+ {name: "redirect is not a verdict", key: projectKey, status: 302, body: ``, wantErr: true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ ts, _, _ := newVerifyServer(t, tt.status, tt.body)+ s := scannerFor(ts)++ results, err := s.FromData(context.Background(), true, []byte("key="+tt.key))+ if err != nil {+ t.Fatalf("FromData error: %v", err)+ }+ if len(results) != 1 {+ t.Fatalf("expected 1 result, got %d", len(results))+ }+ r := results[0]+ if r.Verified != tt.wantVerified {+ t.Errorf("Verified = %v, want %v", r.Verified, tt.wantVerified)+ }+ if tt.wantErr && r.VerificationError() == nil {+ t.Error("expected a verification error, got nil")+ }+ if !tt.wantErr && r.VerificationError() != nil {+ t.Errorf("unexpected verification error: %v", r.VerificationError())+ }+ if got := r.ExtraData["restriction"]; got != tt.wantRestriction {+ t.Errorf("ExtraData restriction = %q, want %q", got, tt.wantRestriction)+ }+ if r.ExtraData["key_type"] == "" {+ t.Error("key_type must survive verification")+ }+ })+ }+}++func TestComposio_Verification_ErrorNeverContainsKey(t *testing.T) {+ ts, _, _ := newVerifyServer(t, http.StatusUnauthorized, bodyAccessDenied)+ s := scannerFor(ts)++ results, err := s.FromData(context.Background(), true, []byte("key="+projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ vErr := results[0].VerificationError()+ if vErr == nil {+ t.Fatal("expected a verification error")+ }+ if msg := vErr.Error(); strings.Contains(msg, projectKey) {+ t.Errorf("verification error leaks the key: %s", msg)+ }+}++func TestComposio_Verification_SkippedWhenVerifyIsFalse(t *testing.T) {+ ts, _, calls := newVerifyServer(t, http.StatusOK, `{}`)+ s := scannerFor(ts)++ results, err := s.FromData(context.Background(), false, []byte("key="+projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ if *calls != 0 {+ t.Errorf("verify=false must not call the API, saw %d requests", *calls)+ }+ if results[0].Verified {+ t.Error("unverified scan must not mark the key verified")+ }+}++func TestComposio_Verification_NoEndpointsNoRequest(t *testing.T) {+ ts, _, calls := newVerifyServer(t, http.StatusOK, `{}`)+ s := Scanner{}+ s.SetCloudEndpoint(ts.URL)+ s.UseCloudEndpoint(false)++ results, err := s.FromData(context.Background(), true, []byte("key="+projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ if *calls != 0 {+ t.Errorf("no configured endpoints must mean no request, saw %d", *calls)+ }+ if results[0].Verified || results[0].VerificationError() != nil {+ t.Error("with no endpoints the result stays unverified and error-free")+ }+}++func TestComposio_Verification_LaterEndpointClearsEarlierError(t *testing.T) {+ ts500, _, _ := newVerifyServer(t, http.StatusInternalServerError, ``)+ ts200, _, _ := newVerifyServer(t, http.StatusOK, `{}`)+ s := Scanner{}+ if err := s.SetConfiguredEndpoints(ts500.URL, ts200.URL); err != nil {+ t.Fatal(err)+ }++ results, err := s.FromData(context.Background(), true, []byte("key="+projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ if !results[0].Verified {+ t.Error("second endpoint answered 200, key must be verified")+ }+ if results[0].VerificationError() != nil {+ t.Errorf("earlier 500 must be cleared by the later 200: %v", results[0].VerificationError())+ }+ if got := results[0].ExtraData["endpoint"]; got != ts200.URL {+ t.Errorf("endpoint = %q, want %q", got, ts200.URL)+ }+}++func TestComposio_Verification_DeadOnOneEndpointKeepsEarlierError(t *testing.T) {+ ts500, _, _ := newVerifyServer(t, http.StatusInternalServerError, ``)+ tsDead, _, _ := newVerifyServer(t, http.StatusUnauthorized, bodyProjectInvalid)+ s := Scanner{}+ if err := s.SetConfiguredEndpoints(ts500.URL, tsDead.URL); err != nil {+ t.Fatal(err)+ }++ results, err := s.FromData(context.Background(), true, []byte("key="+projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ if results[0].Verified {+ t.Error("a clean 401 must not verify")+ }+ if results[0].VerificationError() == nil {+ t.Error("a clean 401 from one endpoint must not erase the 500 from another")+ }+}++func TestComposio_CloudEndpoint(t *testing.T) {+ if got := (Scanner{}).CloudEndpoint(); got != "https://backend.composio.dev" {+ t.Errorf("CloudEndpoint() = %q", got)+ }+}++func TestComposio_RotationGuideResolves(t *testing.T) {+ results, err := Scanner{}.FromData(context.Background(), false, []byte(projectKey))+ if err != nil || len(results) != 1 {+ t.Fatalf("expected 1 result, got %d (err %v)", len(results), err)+ }+ wantGuide := "https://docs.composio.dev/reference/api-reference/api-keys/postApiKeyRevocation"+ if got := results[0].ExtraData["rotation_guide"]; got != wantGuide {+ t.Errorf("rotation_guide = %q", got)+ }+}++// Verifier auth is configured on the scanner, not read from scanned data, so+// the only thing that attaches the operator's access token is building the+// verification client with VerificationClient. A detector that skips that+// wrap still accepts auth and sends the request unauthenticated, which an+// auth proxy answers as if every key were dead.+func TestComposio_Verification_AttachesVerifierAuthToken(t *testing.T) {+ ts, captured, _ := newVerifyServer(t, http.StatusOK, `{}`)+ idp := verifierauthtest.NewIdP(t)++ s := Scanner{}+ if err := s.SetConfiguredEndpoints(ts.URL); err != nil {+ t.Fatalf("SetConfiguredEndpoints: %v", err)+ }+ s.SetVerifierAuth(verifierauthtest.Config(t, idp, "X-Auth-Proxy-Token"))++ results, err := s.FromData(context.Background(), true, []byte("key="+projectKey))+ if err != nil {+ t.Fatalf("FromData error: %v", err)+ }+ if len(results) != 1 {+ t.Fatalf("expected 1 result, got %d", len(results))+ }++ if want := "Bearer " + verifierauthtest.AccessToken; captured.headers.Get("X-Auth-Proxy-Token") != want {+ t.Errorf("X-Auth-Proxy-Token = %q, want %q",+ captured.headers.Get("X-Auth-Proxy-Token"), want)+ }+ // The key itself still travels in its own header, untouched by the wrap.+ if got := captured.headers.Get("x-api-key"); got != projectKey {+ t.Errorf("x-api-key = %q, want the key", got)+ }+ if !results[0].Verified {+ t.Error("200 through the auth proxy must verify the key")+ }+}diff --git a/pkg/engine/defaults/defaults.go b/pkg/engine/defaults/defaults.goindex ef857e851..9d085cf18 100644--- a/pkg/engine/defaults/defaults.go+++ b/pkg/engine/defaults/defaults.go@@ -193,6 +193,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/detectors/commercejs""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/commodities""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/companyhub"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/composio""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/confluent""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/contentfulpersonalaccesstoken""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/conversiontools"@@ -1105,6 +1106,7 @@ func buildDetectorList() []detectors.Detector {&commercejs.Scanner{},&commodities.Scanner{},&companyhub.Scanner{},+ &composio.Scanner{},&confluencedatacenter.Scanner{},&confluent.Scanner{},&contentfulpersonalaccesstoken.Scanner{},@@ -1912,6 +1914,8 @@ func buildDetectorList() []detectors.Detector {return !feature.HumioAPITokenDetectorEnabled.Load()case *resend.Scanner:return !feature.ResendDetectorEnabled.Load()+ case *composio.Scanner:+ return !feature.ComposioDetectorEnabled.Load()case *weightsandbiasesv2.Scanner:return !feature.WeightsAndBiasesV2DetectorEnabled.Load()case *kong.Scanner:diff --git a/pkg/engine/defaults/defaults_test.go b/pkg/engine/defaults/defaults_test.goindex d78eae2bc..14ef6ad1f 100644--- a/pkg/engine/defaults/defaults_test.go+++ b/pkg/engine/defaults/defaults_test.go@@ -156,6 +156,7 @@ var excludedFromDefaultList = map[detector_typepb.DetectorType]struct{}{detector_typepb.DetectorType_KongKonnect: {},detector_typepb.DetectorType_SonarQube: {},detector_typepb.DetectorType_Infisical: {},+ detector_typepb.DetectorType_Composio: {},// Reserved / special types.detector_typepb.DetectorType_CustomRegex: {}, // added dynamically via engine config, not via buildDetectorList()diff --git a/pkg/feature/feature.go b/pkg/feature/feature.goindex e9bee68ef..833f09d74 100644--- a/pkg/feature/feature.go+++ b/pkg/feature/feature.go@@ -52,6 +52,7 @@ var (MSTeamsWebhookV2DetectorEnabled atomic.BoolSolarwindsDetectorEnabled atomic.BoolResendDetectorEnabled atomic.Bool+ ComposioDetectorEnabled atomic.BoolWeightsAndBiasesV2DetectorEnabled atomic.BoolHumioAPITokenDetectorEnabled atomic.BoolEnableS3UnitProgress atomic.Bool // count each S3 bucket during a unit scan to report progress inside itdiff --git a/pkg/pb/detector_typepb/detector_type.pb.go b/pkg/pb/detector_typepb/detector_type.pb.goindex 567d834dd..e9ddc6eb4 100644--- a/pkg/pb/detector_typepb/detector_type.pb.go+++ b/pkg/pb/detector_typepb/detector_type.pb.go@@ -1132,6 +1132,7 @@ const (DetectorType_LambdaCloud DetectorType = 1074DetectorType_Infisical DetectorType = 1075DetectorType_Fireworks DetectorType = 1076+ DetectorType_Composio DetectorType = 1077)// Enum value maps for DetectorType.@@ -2210,6 +2211,7 @@ var (1074: "LambdaCloud",1075: "Infisical",1076: "Fireworks",+ 1077: "Composio",}DetectorType_value = map[string]int32{"Alibaba": 0,@@ -3285,6 +3287,7 @@ var ("LambdaCloud": 1074,"Infisical": 1075,"Fireworks": 1076,+ "Composio": 1077,})@@ -3320,7 +3323,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, 0xe8, 0x8c, 0x01, 0x0a, 0x0c, 0x44, 0x65, 0x74, 0x65, 0x63, 0x74,+ 0x74, 0x79, 0x70, 0x65, 0x2a, 0xf7, 0x8c, 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,@@ -4447,11 +4450,12 @@ var file_detector_type_proto_rawDesc = []byte{0x0a, 0x0b, 0x4c, 0x61, 0x6d, 0x62, 0x64, 0x61, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x10, 0xb2, 0x08,0x12, 0x0e, 0x0a, 0x09, 0x49, 0x6e, 0x66, 0x69, 0x73, 0x69, 0x63, 0x61, 0x6c, 0x10, 0xb3, 0x08,0x12, 0x0e, 0x0a, 0x09, 0x46, 0x69, 0x72, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x10, 0xb4, 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,+ 0x12, 0x0d, 0x0a, 0x08, 0x43, 0x6f, 0x6d, 0x70, 0x6f, 0x73, 0x69, 0x6f, 0x10, 0xb5, 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 cef726df6..254fbcba6 100644--- a/proto/detector_type.proto+++ b/proto/detector_type.proto@@ -1078,4 +1078,5 @@ enum DetectorType {LambdaCloud = 1074;Infisical = 1075;Fireworks = 1076;+ Composio = 1077;}