Skip to content

Find, verify, and analyze leaked credentials

Add xAI analyzer (#5456)

Frenchief6984be151aa
diff --git a/pkg/analyzer/analyzers/analyzers.go b/pkg/analyzer/analyzers/analyzers.go
index f2deaecb3..600cbd6f0 100644
--- a/pkg/analyzer/analyzers/analyzers.go
+++ b/pkg/analyzer/analyzers/analyzers.go
@@ -105,6 +105,7 @@ const (
AnalyzerTypeDropbox
AnalyzerTypeDataBricks
AnalyzerTypeJira
+ AnalyzerTypeXAI
// Add new items here with AnalyzerType prefix
)
@@ -154,6 +155,7 @@ var analyzerTypeStrings = map[AnalyzerType]string{
AnalyzerTypeDropbox: "Dropbox",
AnalyzerTypeDataBricks: "DataBricks",
AnalyzerTypeJira: "Jira",
+ AnalyzerTypeXAI: "XAI",
// Add new mappings here
}
diff --git a/pkg/analyzer/analyzers/xai/permissions.go b/pkg/analyzer/analyzers/xai/permissions.go
new file mode 100644
index 000000000..fdf5d95b4
--- /dev/null
+++ b/pkg/analyzer/analyzers/xai/permissions.go
@@ -0,0 +1,66 @@
+// Code generated by go generate; DO NOT EDIT.
+package xai
+
+import "errors"
+
+type Permission int
+
+const (
+ Invalid Permission = iota
+ EndpointAccess Permission = iota
+ ModelAccess Permission = iota
+)
+
+var (
+ PermissionStrings = map[Permission]string{
+ EndpointAccess: "endpoint_access",
+ ModelAccess: "model_access",
+ }
+
+ StringToPermission = map[string]Permission{
+ "endpoint_access": EndpointAccess,
+ "model_access": ModelAccess,
+ }
+
+ PermissionIDs = map[Permission]int{
+ EndpointAccess: 1,
+ ModelAccess: 2,
+ }
+
+ IdToPermission = map[int]Permission{
+ 1: EndpointAccess,
+ 2: ModelAccess,
+ }
+)
+
+// ToString converts a Permission enum to its string representation
+func (p Permission) ToString() (string, error) {
+ if str, ok := PermissionStrings[p]; ok {
+ return str, nil
+ }
+ return "", errors.New("invalid permission")
+}
+
+// ToID converts a Permission enum to its ID
+func (p Permission) ToID() (int, error) {
+ if id, ok := PermissionIDs[p]; ok {
+ return id, nil
+ }
+ return 0, errors.New("invalid permission")
+}
+
+// PermissionFromString converts a string representation to its Permission enum
+func PermissionFromString(s string) (Permission, error) {
+ if p, ok := StringToPermission[s]; ok {
+ return p, nil
+ }
+ return 0, errors.New("invalid permission string")
+}
+
+// PermissionFromID converts an ID to its Permission enum
+func PermissionFromID(id int) (Permission, error) {
+ if p, ok := IdToPermission[id]; ok {
+ return p, nil
+ }
+ return 0, errors.New("invalid permission ID")
+}
diff --git a/pkg/analyzer/analyzers/xai/permissions.yaml b/pkg/analyzer/analyzers/xai/permissions.yaml
new file mode 100644
index 000000000..2ee2c2bf8
--- /dev/null
+++ b/pkg/analyzer/analyzers/xai/permissions.yaml
@@ -0,0 +1,3 @@
+permissions:
+ - endpoint_access
+ - model_access
diff --git a/pkg/analyzer/analyzers/xai/requests.go b/pkg/analyzer/analyzers/xai/requests.go
new file mode 100644
index 000000000..74cafb6ed
--- /dev/null
+++ b/pkg/analyzer/analyzers/xai/requests.go
@@ -0,0 +1,139 @@
+package xai
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+const (
+ apiKeyEndpoint = "https://api.x.ai/v1/api-key"
+ modelsEndpoint = "https://api.x.ai/v1/models"
+
+ aclPrefix = "api-key:"
+ aclEndpoint = "endpoint"
+ aclModel = "model"
+ aclWildcard = "*"
+)
+
+type apiKeyResponse struct {
+ ACLs []string `json:"acls"`
+ APIKeyBlocked bool `json:"api_key_blocked"`
+ APIKeyDisabled bool `json:"api_key_disabled"`
+ APIKeyID string `json:"api_key_id"`
+ CreateTime string `json:"create_time"`
+ ModifiedBy string `json:"modified_by"`
+ ModifyTime string `json:"modify_time"`
+ Name string `json:"name"`
+ RedactedAPIKey string `json:"redacted_api_key"`
+ TeamBlocked bool `json:"team_blocked"`
+ TeamID string `json:"team_id"`
+ UserID string `json:"user_id"`
+}
+
+type modelsResponse struct {
+ Data []model `json:"data"`
+}
+
+type model struct {
+ ID string `json:"id"`
+ Aliases []string `json:"aliases"`
+ OwnedBy string `json:"owned_by"`
+ ContextLength *int `json:"context_length"`
+}
+
+func makeXAIRequest(ctx context.Context, client *http.Client, url, key string) ([]byte, int, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
+ if err != nil {
+ return nil, 0, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Authorization", "Bearer "+key)
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, 0, fmt.Errorf("failed to send request: %w", err)
+ }
+
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, 0, fmt.Errorf("failed to read response body: %w", err)
+ }
+
+ return body, resp.StatusCode, nil
+}
+
+func fetchAPIKeyInfo(ctx context.Context, client *http.Client, key string) (*apiKeyResponse, error) {
+ body, statusCode, err := makeXAIRequest(ctx, client, apiKeyEndpoint, key)
+ if err != nil {
+ return nil, err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var info apiKeyResponse
+ if err := json.Unmarshal(body, &info); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal api key response: %w", err)
+ }
+ return &info, nil
+ case http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden:
+ return nil, fmt.Errorf("invalid xAI API key: status code %d", statusCode)
+ default:
+ return nil, fmt.Errorf("unexpected status code %d while fetching api key info", statusCode)
+ }
+}
+
+// fetchModels returns ok=false, without error, when the key's ACLs do not
+// permit listing models; callers then fall back to the models named in the ACLs.
+func fetchModels(ctx context.Context, client *http.Client, key string) ([]model, bool, error) {
+ body, statusCode, err := makeXAIRequest(ctx, client, modelsEndpoint, key)
+ if err != nil {
+ return nil, false, err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var models modelsResponse
+ if err := json.Unmarshal(body, &models); err != nil {
+ return nil, false, fmt.Errorf("failed to unmarshal models response: %w", err)
+ }
+ return models.Data, true, nil
+ case http.StatusForbidden, http.StatusNotFound:
+ return nil, false, nil
+ default:
+ return nil, false, fmt.Errorf("unexpected status code %d while fetching models", statusCode)
+ }
+}
+
+// parseACLs splits ACLs of the form api-key:<kind>:<name> into allowed
+// endpoints and models. ACLs in any other form are returned unparsed.
+func parseACLs(acls []string) (endpoints, models, unknown []string) {
+ for _, acl := range acls {
+ kind, name, ok := strings.Cut(strings.TrimPrefix(acl, aclPrefix), ":")
+ if !ok || !strings.HasPrefix(acl, aclPrefix) || name == "" {
+ unknown = append(unknown, acl)
+ continue
+ }
+
+ switch kind {
+ case aclEndpoint:
+ endpoints = append(endpoints, name)
+ case aclModel:
+ models = append(models, name)
+ default:
+ unknown = append(unknown, acl)
+ }
+ }
+
+ return endpoints, models, unknown
+}
diff --git a/pkg/analyzer/analyzers/xai/xai.go b/pkg/analyzer/analyzers/xai/xai.go
new file mode 100644
index 000000000..75ce7f5a3
--- /dev/null
+++ b/pkg/analyzer/analyzers/xai/xai.go
@@ -0,0 +1,280 @@
+//go:generate generate_permissions permissions.yaml permissions.go xai
+package xai
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/fatih/color"
+ "github.com/jedib0t/go-pretty/v6/table"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/config"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+var _ analyzers.Analyzer = (*Analyzer)(nil)
+
+const (
+ resourceTypeTeam = "team"
+ resourceTypeEndpoint = "endpoint"
+ resourceTypeModel = "model"
+)
+
+type Analyzer struct {
+ Cfg *config.Config
+}
+
+// SecretInfo holds the information about the xAI API key.
+type SecretInfo struct {
+ Valid bool
+ Key apiKeyResponse
+ Team XAIResource
+ Endpoints []XAIResource
+ Models []XAIResource
+ // ACLs that are not in the documented api-key:<kind>:<name> form.
+ UnknownACLs []string
+}
+
+// XAIResource is any resource that can be accessed with an xAI API key.
+type XAIResource struct {
+ ID string
+ Name string
+ Type string
+ Metadata map[string]string
+}
+
+func (a Analyzer) Type() analyzers.AnalyzerType {
+ return analyzers.AnalyzerTypeXAI
+}
+
+func (a Analyzer) Analyze(ctx context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
+ key, exist := credInfo["key"]
+ if !exist {
+ err := errors.New("key not found in credentials info")
+ return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", err)
+ }
+
+ secretInfo, err := AnalyzePermissions(ctx, a.Cfg, key)
+ if err != nil {
+ return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
+ }
+
+ return secretInfoToAnalyzerResult(secretInfo), nil
+}
+
+func AnalyzeAndPrintPermissions(cfg *config.Config, key string) {
+ info, err := AnalyzePermissions(context.Background(), cfg, key)
+ if err != nil {
+ color.Red("[x] Error : %s", err.Error())
+ return
+ }
+
+ printKeyInfo(info)
+ if !info.Valid {
+ return
+ }
+
+ printResources("Endpoints", info.Endpoints)
+ printResources("Models", info.Models)
+
+ if len(info.UnknownACLs) > 0 {
+ color.Yellow("\n[i] Unrecognized ACLs: %s", strings.Join(info.UnknownACLs, ", "))
+ }
+}
+
+func AnalyzePermissions(ctx context.Context, cfg *config.Config, key string) (*SecretInfo, error) {
+ return analyzePermissions(ctx, analyzers.NewAnalyzeClient(cfg), key)
+}
+
+func analyzePermissions(ctx context.Context, client *http.Client, key string) (*SecretInfo, error) {
+ keyInfo, err := fetchAPIKeyInfo(ctx, client, key)
+ if err != nil {
+ return nil, err
+ }
+
+ secretInfo := &SecretInfo{
+ Key: *keyInfo,
+ Team: XAIResource{
+ ID: "x.ai/team/" + keyInfo.TeamID,
+ Name: keyInfo.TeamID,
+ Type: resourceTypeTeam,
+ },
+ // The key endpoint answers 200 for blocked and disabled keys too, but
+ // such keys cannot call the API.
+ Valid: !keyInfo.APIKeyBlocked && !keyInfo.APIKeyDisabled && !keyInfo.TeamBlocked,
+ }
+ if !secretInfo.Valid {
+ return secretInfo, nil
+ }
+
+ allowedEndpoints, allowedModels, unknown := parseACLs(keyInfo.ACLs)
+ secretInfo.UnknownACLs = unknown
+
+ for _, endpoint := range allowedEndpoints {
+ secretInfo.Endpoints = append(secretInfo.Endpoints, XAIResource{
+ ID: fmt.Sprintf("x.ai/team/%s/endpoint/%s", keyInfo.TeamID, endpoint),
+ Name: endpoint,
+ Type: resourceTypeEndpoint,
+ })
+ }
+
+ models, listed, err := fetchModels(ctx, client, key)
+ if err != nil {
+ return nil, err
+ }
+ secretInfo.Models = accessibleModels(keyInfo.TeamID, allowedModels, models, listed)
+
+ return secretInfo, nil
+}
+
+// accessibleModels intersects the models the API lists with the models the
+// key's ACLs allow. Models named in the ACLs but absent from the listing are
+// still reported, since the ACL alone grants access to them.
+func accessibleModels(teamID string, allowed []string, listedModels []model, listed bool) []XAIResource {
+ wildcard := slices.Contains(allowed, aclWildcard)
+ matched := make(map[string]bool, len(allowed))
+ var resources []XAIResource
+
+ if listed {
+ for _, m := range listedModels {
+ names := append([]string{m.ID}, m.Aliases...)
+ isAllowed := wildcard
+ for _, name := range names {
+ if slices.Contains(allowed, name) {
+ matched[name] = true
+ isAllowed = true
+ }
+ }
+ if !isAllowed {
+ continue
+ }
+
+ metadata := map[string]string{"owned_by": m.OwnedBy}
+ if len(m.Aliases) > 0 {
+ metadata["aliases"] = strings.Join(m.Aliases, ",")
+ }
+ if m.ContextLength != nil {
+ metadata["context_length"] = strconv.Itoa(*m.ContextLength)
+ }
+
+ resources = append(resources, XAIResource{
+ ID: fmt.Sprintf("x.ai/team/%s/model/%s", teamID, m.ID),
+ Name: m.ID,
+ Type: resourceTypeModel,
+ Metadata: metadata,
+ })
+ }
+ }
+
+ for _, name := range allowed {
+ if matched[name] || (listed && name == aclWildcard) {
+ continue
+ }
+ resources = append(resources, XAIResource{
+ ID: fmt.Sprintf("x.ai/team/%s/model/%s", teamID, name),
+ Name: name,
+ Type: resourceTypeModel,
+ })
+ }
+
+ return resources
+}
+
+func secretInfoToAnalyzerResult(info *SecretInfo) *analyzers.AnalyzerResult {
+ if info == nil {
+ return nil
+ }
+
+ result := analyzers.AnalyzerResult{
+ AnalyzerType: analyzers.AnalyzerTypeXAI,
+ Metadata: map[string]any{
+ "Valid_Key": info.Valid,
+ "key_name": info.Key.Name,
+ "api_key_id": info.Key.APIKeyID,
+ "redacted_api_key": info.Key.RedactedAPIKey,
+ "user_id": info.Key.UserID,
+ "team_id": info.Key.TeamID,
+ "acls": strings.Join(info.Key.ACLs, ","),
+ "api_key_blocked": info.Key.APIKeyBlocked,
+ "api_key_disabled": info.Key.APIKeyDisabled,
+ "team_blocked": info.Key.TeamBlocked,
+ "create_time": info.Key.CreateTime,
+ "modify_time": info.Key.ModifyTime,
+ },
+ Bindings: make([]analyzers.Binding, 0, len(info.Endpoints)+len(info.Models)),
+ }
+
+ team := analyzers.Resource{
+ Name: info.Team.Name,
+ FullyQualifiedName: info.Team.ID,
+ Type: info.Team.Type,
+ }
+
+ addBindings := func(resources []XAIResource, permission Permission) {
+ for _, res := range resources {
+ metadata := make(map[string]any, len(res.Metadata))
+ for k, v := range res.Metadata {
+ metadata[k] = v
+ }
+ result.Bindings = append(result.Bindings, analyzers.Binding{
+ Resource: analyzers.Resource{
+ Name: res.Name,
+ FullyQualifiedName: res.ID,
+ Type: res.Type,
+ Metadata: metadata,
+ Parent: &team,
+ },
+ Permission: analyzers.Permission{Value: PermissionStrings[permission]},
+ })
+ }
+ }
+ addBindings(info.Endpoints, EndpointAccess)
+ addBindings(info.Models, ModelAccess)
+
+ return &result
+}
+
+func printKeyInfo(info *SecretInfo) {
+ if info.Valid {
+ color.Green("[!] Valid xAI API Key\n\n")
+ } else {
+ color.Red("[x] xAI API Key exists but cannot be used (blocked: %t, disabled: %t, team blocked: %t)\n\n",
+ info.Key.APIKeyBlocked, info.Key.APIKeyDisabled, info.Key.TeamBlocked)
+ }
+
+ color.Yellow("[i] Key Information:")
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Name", "Key ID", "Redacted Key", "Team ID", "User ID", "Created"})
+ t.AppendRow(table.Row{
+ color.GreenString(info.Key.Name),
+ color.GreenString(info.Key.APIKeyID),
+ color.GreenString(info.Key.RedactedAPIKey),
+ color.GreenString(info.Key.TeamID),
+ color.GreenString(info.Key.UserID),
+ color.GreenString(info.Key.CreateTime),
+ })
+ t.Render()
+}
+
+func printResources(title string, resources []XAIResource) {
+ color.Green("\n[i] %s:", title)
+ if len(resources) == 0 {
+ color.Yellow("None")
+ return
+ }
+
+ t := table.NewWriter()
+ t.SetOutputMirror(os.Stdout)
+ t.AppendHeader(table.Row{"Name", "Fully Qualified Name"})
+ for _, res := range resources {
+ t.AppendRow(table.Row{color.GreenString(res.Name), color.GreenString(res.ID)})
+ }
+ t.Render()
+}
diff --git a/pkg/analyzer/analyzers/xai/xai_test.go b/pkg/analyzer/analyzers/xai/xai_test.go
new file mode 100644
index 000000000..621ad1550
--- /dev/null
+++ b/pkg/analyzer/analyzers/xai/xai_test.go
@@ -0,0 +1,209 @@
+package xai
+
+import (
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/config"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/common"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+type stubResponse struct {
+ status int
+ body string
+}
+
+type stubTransport map[string]stubResponse
+
+func (s stubTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ res, ok := s[req.URL.String()]
+ if !ok {
+ res = stubResponse{status: http.StatusNotFound, body: "{}"}
+ }
+ return &http.Response{
+ StatusCode: res.status,
+ Body: io.NopCloser(strings.NewReader(res.body)),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+}
+
+func stubClient(apiKey, models stubResponse) *http.Client {
+ return &http.Client{Transport: stubTransport{
+ apiKeyEndpoint: apiKey,
+ modelsEndpoint: models,
+ }}
+}
+
+const modelsBody = `{"object":"list","data":[
+ {"id":"grok-4","aliases":["grok-4-latest"],"owned_by":"xai","context_length":256000},
+ {"id":"grok-3-mini","aliases":[],"owned_by":"xai"}
+]}`
+
+func apiKeyBody(acls string, blocked, disabled bool) string {
+ b := map[bool]string{true: "true", false: "false"}
+ return `{"acls":[` + acls + `],"api_key_blocked":` + b[blocked] + `,"api_key_disabled":` + b[disabled] +
+ `,"api_key_id":"key-1","create_time":"2026-01-01T00:00:00Z","modified_by":"user-1",` +
+ `"modify_time":"2026-01-01T00:00:00Z","name":"ci key","redacted_api_key":"xai-...abcd",` +
+ `"team_blocked":false,"team_id":"team-1","user_id":"user-1"}`
+}
+
+func bindingSummary(result *analyzers.AnalyzerResult) []string {
+ var out []string
+ for _, b := range result.Bindings {
+ out = append(out, b.Resource.Type+"|"+b.Resource.FullyQualifiedName+"|"+b.Permission.Value+"|"+b.Resource.Parent.FullyQualifiedName)
+ }
+ return out
+}
+
+func TestAnalyzePermissions(t *testing.T) {
+ tests := []struct {
+ name string
+ apiKey stubResponse
+ models stubResponse
+ wantErr bool
+ wantValid bool
+ wantBindings []string
+ wantUnknown []string
+ }{
+ {
+ name: "wildcard acls grant every listed model",
+ apiKey: stubResponse{http.StatusOK, apiKeyBody(`"api-key:endpoint:*","api-key:model:*"`, false, false)},
+ models: stubResponse{http.StatusOK, modelsBody},
+ wantValid: true,
+ wantBindings: []string{
+ "endpoint|x.ai/team/team-1/endpoint/*|endpoint_access|x.ai/team/team-1",
+ "model|x.ai/team/team-1/model/grok-4|model_access|x.ai/team/team-1",
+ "model|x.ai/team/team-1/model/grok-3-mini|model_access|x.ai/team/team-1",
+ },
+ },
+ {
+ name: "model acl matches by alias and keeps unlisted acl models",
+ apiKey: stubResponse{http.StatusOK, apiKeyBody(`"api-key:endpoint:chat","api-key:model:grok-4-latest","api-key:model:grok-2-image","team:admin"`, false, false)},
+ models: stubResponse{http.StatusOK, modelsBody},
+ wantValid: true,
+ wantBindings: []string{
+ "endpoint|x.ai/team/team-1/endpoint/chat|endpoint_access|x.ai/team/team-1",
+ "model|x.ai/team/team-1/model/grok-4|model_access|x.ai/team/team-1",
+ "model|x.ai/team/team-1/model/grok-2-image|model_access|x.ai/team/team-1",
+ },
+ wantUnknown: []string{"team:admin"},
+ },
+ {
+ name: "models endpoint forbidden falls back to acl models",
+ apiKey: stubResponse{http.StatusOK, apiKeyBody(`"api-key:endpoint:chat","api-key:model:*"`, false, false)},
+ models: stubResponse{http.StatusForbidden, `{"error":"forbidden"}`},
+ wantValid: true,
+ wantBindings: []string{
+ "endpoint|x.ai/team/team-1/endpoint/chat|endpoint_access|x.ai/team/team-1",
+ "model|x.ai/team/team-1/model/*|model_access|x.ai/team/team-1",
+ },
+ },
+ {
+ name: "blocked key is reported but not valid",
+ apiKey: stubResponse{http.StatusOK, apiKeyBody(`"api-key:endpoint:*","api-key:model:*"`, true, false)},
+ wantValid: false,
+ },
+ {
+ name: "disabled key is reported but not valid",
+ apiKey: stubResponse{http.StatusOK, apiKeyBody(`"api-key:endpoint:*","api-key:model:*"`, false, true)},
+ wantValid: false,
+ },
+ {
+ name: "invalid key",
+ apiKey: stubResponse{http.StatusUnauthorized, `{"error":"Incorrect API key provided"}`},
+ wantErr: true,
+ },
+ {
+ name: "unexpected status",
+ apiKey: stubResponse{http.StatusInternalServerError, `{}`},
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ info, err := analyzePermissions(context.Background(), stubClient(tt.apiKey, tt.models), "xai-test")
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("analyzePermissions() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantErr {
+ return
+ }
+
+ if info.Valid != tt.wantValid {
+ t.Errorf("Valid = %v, want %v", info.Valid, tt.wantValid)
+ }
+
+ result := secretInfoToAnalyzerResult(info)
+ if result.AnalyzerType != analyzers.AnalyzerTypeXAI {
+ t.Errorf("AnalyzerType = %v, want %v", result.AnalyzerType, analyzers.AnalyzerTypeXAI)
+ }
+ if result.Metadata["Valid_Key"] != tt.wantValid || result.Metadata["key_name"] != "ci key" {
+ t.Errorf("unexpected metadata: %v", result.Metadata)
+ }
+ if diff := cmp.Diff(tt.wantBindings, bindingSummary(result)); diff != "" {
+ t.Errorf("bindings mismatch (-want +got):\n%s", diff)
+ }
+ if diff := cmp.Diff(tt.wantUnknown, info.UnknownACLs); diff != "" {
+ t.Errorf("unknown ACLs mismatch (-want +got):\n%s", diff)
+ }
+ })
+ }
+}
+
+func TestAnalyzer_MissingKey(t *testing.T) {
+ _, err := Analyzer{}.Analyze(context.Background(), map[string]string{})
+ if err == nil {
+ t.Fatal("expected error for missing key")
+ }
+}
+
+func TestAnalyzer_Analyze(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute*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)
+ }
+
+ tests := []struct {
+ name string
+ secret string
+ wantErr bool
+ }{
+ {name: "valid xai key", secret: testSecrets.MustGetField("XAI")},
+ {name: "invalid xai key", secret: testSecrets.MustGetField("XAI_INACTIVE"), wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := Analyzer{Cfg: &config.Config{}}.Analyze(ctx, map[string]string{"key": tt.secret})
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("Analyzer.Analyze() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ if tt.wantErr {
+ return
+ }
+
+ if got.Metadata["Valid_Key"] != true {
+ t.Errorf("expected a usable key, got metadata %v", got.Metadata)
+ }
+ if len(got.Bindings) == 0 {
+ t.Error("expected endpoint and model bindings")
+ }
+ for _, b := range got.Bindings {
+ if _, ok := StringToPermission[b.Permission.Value]; !ok {
+ t.Errorf("binding %s has unknown permission %q", b.Resource.FullyQualifiedName, b.Permission.Value)
+ }
+ }
+ })
+ }
+}
diff --git a/pkg/analyzer/cli.go b/pkg/analyzer/cli.go
index b96b3f20c..c1b109fb9 100644
--- a/pkg/analyzer/cli.go
+++ b/pkg/analyzer/cli.go
@@ -48,6 +48,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/square"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/stripe"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/twilio"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/xai"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/config"
)
@@ -151,5 +152,8 @@ func Run(keyType string, secretInfo SecretInfo) {
databricks.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["domain"], secretInfo.Parts["token"])
case "jira":
jira.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["domain"], secretInfo.Parts["email"], secretInfo.Parts["token"])
+
+ case "xai":
+ xai.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
}
}