Skip to content

Find, verify, and analyze leaked credentials

LaunchDarkly Token Analyzer (#3948)

Kashif Khanc1f2e9122392
diff --git a/pkg/analyzer/analyzers/analyzers.go b/pkg/analyzer/analyzers/analyzers.go
index 7928cbcd4..db01f72fc 100644
--- a/pkg/analyzer/analyzers/analyzers.go
+++ b/pkg/analyzer/analyzers/analyzers.go
@@ -8,6 +8,7 @@ import (
"sort"
"github.com/fatih/color"
+
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
)
@@ -90,6 +91,7 @@ const (
AnalyzerTypeAirtableOAuth
AnalyzerTypeAirtablePat
AnalyzerTypeGroq
+ AnalyzerTypeLaunchDarkly
// Add new items here with AnalyzerType prefix
)
@@ -126,6 +128,7 @@ var analyzerTypeStrings = map[AnalyzerType]string{
AnalyzerTypeAirtableOAuth: "AirtableOAuth",
AnalyzerTypeAirtablePat: "AirtablePat",
AnalyzerTypeGroq: "Groq",
+ AnalyzerTypeLaunchDarkly: "LaunchDarkly",
// Add new mappings here
}
diff --git a/pkg/analyzer/analyzers/launchdarkly/launchdarkly.go b/pkg/analyzer/analyzers/launchdarkly/launchdarkly.go
new file mode 100644
index 000000000..eb2d9c9f3
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/launchdarkly.go
@@ -0,0 +1,204 @@
+//go:generate generate_permissions permissions.yaml permissions.go launchdarkly
+package launchdarkly
+
+import (
+ "errors"
+ "fmt"
+ "os"
+
+ "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)
+
+type Analyzer struct {
+ Cfg *config.Config
+}
+
+func (a Analyzer) Type() analyzers.AnalyzerType {
+ return analyzers.AnalyzerTypeLaunchDarkly
+}
+
+func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
+ // check if the `key` exist in the credentials info
+ key, exist := credInfo["key"]
+ if !exist {
+ return nil, errors.New("key not found in credentials info")
+ }
+
+ info, err := AnalyzePermissions(a.Cfg, key)
+ if err != nil {
+ return nil, err
+ }
+
+ return secretInfoToAnalyzerResult(info), nil
+}
+
+func AnalyzeAndPrintPermissions(cfg *config.Config, token string) {
+ info, err := AnalyzePermissions(cfg, token)
+ if err != nil {
+ // just print the error in cli and continue as a partial success
+ color.Red("[x] Error : %s", err.Error())
+ }
+
+ if info == nil {
+ color.Red("[x] Error : %s", "No information found")
+ return
+ }
+
+ color.Green("[i] Valid LaunchDarkly Token\n")
+ printUser(info.User)
+ printPermissionsType(info.User.Token)
+ printResources(info.Resources)
+
+ color.Yellow("\n[!] Expires: Never")
+}
+
+// AnalyzePermissions will collect all the scopes assigned to token along with resource it can access
+func AnalyzePermissions(cfg *config.Config, token string) (*SecretInfo, error) {
+ // create the http client
+ client := analyzers.NewAnalyzeClient(cfg)
+
+ var secretInfo = &SecretInfo{}
+
+ // capture user information in secretInfo
+ if err := CaptureUserInformation(client, token, secretInfo); err != nil {
+ return nil, fmt.Errorf("failed to fetch caller identity: %v", err)
+ }
+
+ // capture resources in secretInfo
+ if err := CaptureResources(client, token, secretInfo); err != nil {
+ return nil, fmt.Errorf("failed to fetch resources: %v", err)
+ }
+
+ return secretInfo, nil
+}
+
+// secretInfoToAnalyzerResult translate secret info to Analyzer Result
+func secretInfoToAnalyzerResult(info *SecretInfo) *analyzers.AnalyzerResult {
+ if info == nil {
+ return nil
+ }
+
+ result := analyzers.AnalyzerResult{
+ AnalyzerType: analyzers.AnalyzerTypeElevenLabs,
+ Metadata: map[string]any{},
+ Bindings: make([]analyzers.Binding, 0),
+ }
+
+ // extract information from resource to create bindings and append to result bindings
+ for _, resource := range info.Resources {
+ binding := analyzers.Binding{
+ Resource: *secretInfoResourceToAnalyzerResource(resource),
+ Permission: analyzers.Permission{
+ Value: getPermissionType(info.User.Token),
+ },
+ }
+
+ if resource.ParentResource != nil {
+ binding.Resource.Parent = secretInfoResourceToAnalyzerResource(*resource.ParentResource)
+ }
+
+ result.Bindings = append(result.Bindings, binding)
+
+ }
+
+ return &result
+}
+
+// secretInfoResourceToAnalyzerResource translate secret info resource to analyzer resource for binding
+func secretInfoResourceToAnalyzerResource(resource Resource) *analyzers.Resource {
+ analyzerRes := analyzers.Resource{
+ FullyQualifiedName: resource.ID,
+ Name: resource.Name,
+ Type: resource.Type,
+ Metadata: map[string]any{},
+ }
+
+ for key, value := range resource.MetaData {
+ analyzerRes.Metadata[key] = value
+ }
+
+ return &analyzerRes
+}
+
+// getPermissionType return what type of permission is assigned to token
+func getPermissionType(token Token) string {
+ switch {
+ case token.Role != "":
+ return token.Role
+ case token.hasInlineRole():
+ return "Inline Policy"
+ case token.hasCustomRoles():
+ return "Custom Roles"
+ default:
+ return ""
+ }
+}
+
+// printUser print User information from secret info to cli
+func printUser(user User) {
+ // print caller information
+ color.Green("\n[i] User Information:")
+ callerTable := table.NewWriter()
+ callerTable.SetOutputMirror(os.Stdout)
+ callerTable.AppendHeader(table.Row{"Account ID", "Member ID", "Name", "Email", "Role"})
+ callerTable.AppendRow(table.Row{color.GreenString(user.AccountID), color.GreenString(user.MemberID),
+ color.GreenString(user.Name), color.GreenString(user.Email), color.GreenString(user.Role)})
+
+ callerTable.Render()
+
+ // print token information
+ color.Green("\n[i] Token Information")
+ tokenTable := table.NewWriter()
+ tokenTable.SetOutputMirror(os.Stdout)
+
+ tokenTable.AppendHeader(table.Row{"ID", "Name", "Role", "Is Service Token", "Default API Version",
+ "No of Custom Roles Assigned", "Has Inline Policy"})
+
+ tokenTable.AppendRow(table.Row{color.GreenString(user.Token.ID), color.GreenString(user.Token.Name), color.GreenString(user.Token.Role),
+ color.GreenString(fmt.Sprintf("%t", user.Token.IsServiceToken)), color.GreenString(fmt.Sprintf("%d", user.Token.APIVersion)),
+ color.GreenString(fmt.Sprintf("%d", len(user.Token.CustomRoles))), color.GreenString(fmt.Sprintf("%t", user.Token.hasInlineRole()))})
+
+ tokenTable.Render()
+
+ // print custom roles information
+ if !user.Token.hasCustomRoles() {
+ return
+ }
+
+ // print token information
+ color.Green("\n[i] Custom Roles Assigned to Token")
+ rolesTable := table.NewWriter()
+ rolesTable.SetOutputMirror(os.Stdout)
+ rolesTable.AppendHeader(table.Row{"ID", "Key", "Name", "Base Permission", "Assigned to members", "Assigned to teams"})
+ for _, customRole := range user.Token.CustomRoles {
+ rolesTable.AppendRow(table.Row{color.GreenString(customRole.ID), color.GreenString(customRole.Key), color.GreenString(customRole.Name),
+ color.GreenString(customRole.BasePermission), color.GreenString(fmt.Sprintf("%d", customRole.AssignedToMembers)),
+ color.GreenString(fmt.Sprintf("%d", customRole.AssignedToTeams))})
+ }
+ rolesTable.Render()
+}
+
+// printPermissionsType print permissions type token has
+func printPermissionsType(token Token) {
+ // print permission type. It can be either admin, writer, reader or has inline policy or any custom roles assigned
+ color.Green("\n[i] Permission Type: %s", getPermissionType(token))
+}
+
+func printResources(resources []Resource) {
+ // print resources
+ color.Green("\n[i] Resources:")
+ callerTable := table.NewWriter()
+ callerTable.SetOutputMirror(os.Stdout)
+ callerTable.AppendHeader(table.Row{"Name", "Type"})
+ for _, resource := range resources {
+ callerTable.AppendRow(table.Row{color.GreenString(resource.Name), color.GreenString(resource.Type)})
+ }
+ callerTable.Render()
+}
diff --git a/pkg/analyzer/analyzers/launchdarkly/launchdarkly_test.go b/pkg/analyzer/analyzers/launchdarkly/launchdarkly_test.go
new file mode 100644
index 000000000..b52e66f82
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/launchdarkly_test.go
@@ -0,0 +1,102 @@
+package launchdarkly
+
+import (
+ _ "embed"
+ "encoding/json"
+ "sort"
+ "testing"
+ "time"
+
+ "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"
+)
+
+//go:embed result_output.json
+var expectedOutput []byte
+
+func TestAnalyzer_Analyze(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
+ defer cancel()
+ testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors3")
+ if err != nil {
+ t.Fatalf("could not get test secrets from GCP: %s", err)
+ }
+
+ key := testSecrets.MustGetField("LAUNCHDARKLY_TOKEN")
+
+ tests := []struct {
+ name string
+ key string
+ want []byte // JSON string
+ wantErr bool
+ }{
+ {
+ name: "valid LauncgDarkly token",
+ key: key,
+ want: expectedOutput,
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ a := Analyzer{Cfg: &config.Config{}}
+ got, err := a.Analyze(ctx, map[string]string{"key": tt.key})
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Analyzer.Analyze() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ // Bindings need to be in the same order to be comparable
+ sortBindings(got.Bindings)
+
+ // Marshal the actual result to JSON
+ gotJSON, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("could not marshal got to JSON: %s", err)
+ }
+
+ // Parse the expected JSON string
+ var wantObj analyzers.AnalyzerResult
+ if err := json.Unmarshal([]byte(tt.want), &wantObj); err != nil {
+ t.Fatalf("could not unmarshal want JSON string: %s", err)
+ }
+
+ // Bindings need to be in the same order to be comparable
+ sortBindings(wantObj.Bindings)
+
+ // Marshal the expected result to JSON (to normalize)
+ wantJSON, err := json.Marshal(wantObj)
+ if err != nil {
+ t.Fatalf("could not marshal want to JSON: %s", err)
+ }
+
+ // Compare the JSON strings
+ if string(gotJSON) != string(wantJSON) {
+ // Pretty-print both JSON strings for easier comparison
+ var gotIndented, wantIndented []byte
+ gotIndented, err = json.MarshalIndent(got, "", " ")
+ if err != nil {
+ t.Fatalf("could not marshal got to indented JSON: %s", err)
+ }
+ wantIndented, err = json.MarshalIndent(wantObj, "", " ")
+ if err != nil {
+ t.Fatalf("could not marshal want to indented JSON: %s", err)
+ }
+ t.Errorf("Analyzer.Analyze() = %s, want %s", gotIndented, wantIndented)
+ }
+ })
+ }
+}
+
+// Helper function to sort bindings
+func sortBindings(bindings []analyzers.Binding) {
+ sort.SliceStable(bindings, func(i, j int) bool {
+ if bindings[i].Resource.Name == bindings[j].Resource.Name {
+ return bindings[i].Permission.Value < bindings[j].Permission.Value
+ }
+ return bindings[i].Resource.Name < bindings[j].Resource.Name
+ })
+}
diff --git a/pkg/analyzer/analyzers/launchdarkly/models.go b/pkg/analyzer/analyzers/launchdarkly/models.go
new file mode 100644
index 000000000..05dcb6523
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/models.go
@@ -0,0 +1,112 @@
+package launchdarkly
+
+import "sync"
+
+var (
+ MetadataKey = "key"
+
+ // resource types
+ applicationKey = "Application"
+ repositoryKey = "Repository"
+ projectKey = "Project"
+ environmentKey = "Environment"
+ experimentKey = "Experiment"
+ holdoutsKey = "Holdout"
+ membersKey = "Member"
+ destinationsKey = "Destination"
+ templatesKey = "Templates"
+ teamsKey = "Teams"
+ webhooksKey = "Webhooks"
+ featureFlagsKey = "Feature Flags"
+)
+
+type SecretInfo struct {
+ User User
+ Permissions []string
+
+ mu sync.RWMutex
+ Resources []Resource
+}
+
+// User is the information about the user to whom the token belongs
+type User struct {
+ AccountID string // account id. It is the owner id of token as well
+ MemberID string
+ Name string
+ Role string // role of caller
+ Email string
+ Token Token
+}
+
+// Token is the token details
+type Token struct {
+ ID string // id of the token
+ Name string // name of the token
+ CustomRoles []CustomRole // custom roles assigned to the token
+ InlineRole []Policy // any policy statements maybe used in place of a built-in custom role
+ Role string // role of token
+ IsServiceToken bool // is a service token or not
+ APIVersion int // default api version assigned to the token
+}
+
+// CustomRole is a flexible policies providing fine-grained access control to everything in launch darkly
+type CustomRole struct {
+ ID string
+ Key string
+ Name string
+ Polices []Policy
+ BasePermission string
+ AssignedToMembers int
+ AssignedToTeams int
+}
+
+// policy is a set of statements
+type Policy struct {
+ Resources []string
+ NotResources []string
+ Actions []string
+ NotActions []string
+ Effect string
+}
+
+type Resource struct {
+ ID string
+ Name string
+ Permission string
+ Type string
+ ParentResource *Resource
+ MetaData map[string]string
+}
+
+// appendResources append resource to secret info resources list
+func (s *SecretInfo) appendResource(resource Resource) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.Resources = append(s.Resources, resource)
+}
+
+// listResourceByType returns a list of resources matching the given type.
+func (s *SecretInfo) listResourceByType(resourceType string) []Resource {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ resources := make([]Resource, 0, len(s.Resources))
+ for _, resource := range s.Resources {
+ if resource.Type == resourceType {
+ resources = append(resources, resource)
+ }
+ }
+
+ return resources
+}
+
+// hasCustomRoles check if token has any custom roles assigned
+func (t Token) hasCustomRoles() bool {
+ return len(t.CustomRoles) > 0
+}
+
+// hasInlineRole check if token has any inline roles
+func (t Token) hasInlineRole() bool {
+ return len(t.InlineRole) > 0
+}
diff --git a/pkg/analyzer/analyzers/launchdarkly/permissions.go b/pkg/analyzer/analyzers/launchdarkly/permissions.go
new file mode 100644
index 000000000..f4e3b6282
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/permissions.go
@@ -0,0 +1,81 @@
+// Code generated by go generate; DO NOT EDIT.
+package launchdarkly
+
+import "errors"
+
+type Permission int
+
+const (
+ Invalid Permission = iota
+ Admin Permission = iota
+ Writer Permission = iota
+ Reader Permission = iota
+ Inlinepolicy Permission = iota
+ Customroles Permission = iota
+)
+
+var (
+ PermissionStrings = map[Permission]string{
+ Admin: "admin",
+ Writer: "writer",
+ Reader: "reader",
+ Inlinepolicy: "inlinepolicy",
+ Customroles: "customroles",
+ }
+
+ StringToPermission = map[string]Permission{
+ "admin": Admin,
+ "writer": Writer,
+ "reader": Reader,
+ "inlinepolicy": Inlinepolicy,
+ "customroles": Customroles,
+ }
+
+ PermissionIDs = map[Permission]int{
+ Admin: 1,
+ Writer: 2,
+ Reader: 3,
+ Inlinepolicy: 4,
+ Customroles: 5,
+ }
+
+ IdToPermission = map[int]Permission{
+ 1: Admin,
+ 2: Writer,
+ 3: Reader,
+ 4: Inlinepolicy,
+ 5: Customroles,
+ }
+)
+
+// 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/launchdarkly/permissions.yaml b/pkg/analyzer/analyzers/launchdarkly/permissions.yaml
new file mode 100644
index 000000000..8e1dade38
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/permissions.yaml
@@ -0,0 +1,6 @@
+permissions:
+ - admin
+ - writer
+ - reader
+ - inlinepolicy
+ - customroles
\ No newline at end of file
diff --git a/pkg/analyzer/analyzers/launchdarkly/requests.go b/pkg/analyzer/analyzers/launchdarkly/requests.go
new file mode 100644
index 000000000..ce03b3574
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/requests.go
@@ -0,0 +1,741 @@
+package launchdarkly
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "sync"
+ "time"
+)
+
+const defaultTimeout = 5 * time.Second
+
+var (
+ baseURL = "https://app.launchdarkly.com/api"
+
+ endpoints = map[string]string{
+ // user information APIs
+ "callerIdentity": "/v2/caller-identity",
+ "getToken": "/v2/tokens/%s", // require token id
+ "getRole": "/v2/roles/%s", // require role id
+ // resource APIs
+ applicationKey: "/v2/applications",
+ repositoryKey: "/v2/code-refs/repositories",
+ projectKey: "/v2/projects",
+ environmentKey: "/v2/projects/%s/environments", // require project key
+ featureFlagsKey: "/v2/flags/%s", // require project key
+ experimentKey: "/v2/projects/%s/environments/%s/experiments", // require project key and env key
+ holdoutsKey: "/v2/projects/%s/environments/%s/holdouts", // require project key and env key
+ membersKey: "/v2/members",
+ destinationsKey: "/v2/destinations",
+ templatesKey: "/v2/templates",
+ teamsKey: "/v2/teams",
+ webhooksKey: "/v2/webhooks",
+ /*
+ TODO:
+ release piplelines: https://launchdarkly.com/docs/api/release-pipelines-beta/get-all-release-pipelines (Beta)
+ insight deployments: https://launchdarkly.com/docs/api/insights-deployments-beta/get-deployments (Beta)
+ delivery configuration: https://launchdarkly.com/docs/api/integration-delivery-configurations-beta/get-integration-delivery-configuration-by-environment (Beta)
+ metrics: https://launchdarkly.com/docs/api/metrics-beta/get-metric-groups (Beta)
+ */
+ }
+)
+
+// applicationsResponse is the response of /v2/applications API
+type applicationsResponse struct {
+ Items []struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Maintainer struct {
+ Email string `json:"email"`
+ } `json:"_maintainer"`
+ } `json:"items"`
+}
+
+// repositoriesResponse is the response of /v2/code-refs/repositories API
+type repositoriesResponse struct {
+ Items []struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ DefaultBranch string `json:"defaultBranch"`
+ SourceLink string `json:"sourceLink"`
+ Version int `json:"version"`
+ } `json:"items"`
+}
+
+// projectsResponse is the response of /v2/projects API
+type projectsResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Key string `json:"key"`
+ Name string `json:"name"`
+ } `json:"items"`
+}
+
+// featureFlagsResponse is the response of /v2/flags/<project_id> API
+type featureFlagsResponse struct {
+ Items []struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ } `json:"items"`
+}
+
+// environmentsResponse is the response of /v2/projects/<proj_key>/environments API
+type environmentsResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Key string `json:"key"`
+ Name string `json:"name"`
+ } `json:"items"`
+}
+
+// experimentResponse is the response of /v2/projects/<proj_id>/env/<env_id>/experiments
+type experimentResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Key string `json:"key"`
+ Name string `json:"name"`
+ MaintainerID string `json:"_maintainerId"`
+ } `json:"items"`
+}
+
+// membersResponse is the response of /v2/members API
+type membersResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Role string `json:"role"`
+ Email string `json:"email"`
+ FirstName string `json:"firstName"`
+ LastName string `json:"lastName"`
+ } `json:"items"`
+}
+
+// holdoutsResponse is the response of /v2/projects/<project_id>/environments/<env_id>/holdouts API
+type holdoutsResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Name string `json:"name"`
+ Key string `json:"key"`
+ Status string `json:"status"`
+ } `json:"items"`
+}
+
+// destinationsResponse is the response of /v2/destinations API
+type destinationsResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Version int `json:"version"`
+ } `json:"items"`
+}
+
+// templatesResponse is the response of /v2/templates API
+type templatesResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Key string `json:"_key"`
+ Name string `json:"name"`
+ } `json:"items"`
+}
+
+// teamsResponse is the response of /v2/teams API
+type teamsResponse struct {
+ Items []struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Roles struct {
+ TotalCount int `json:"totalCount"`
+ } `json:"roles"`
+ Members struct {
+ TotalCount int `json:"totalCount"`
+ } `json:"members"`
+ Projects struct {
+ TotalCount int `json:"totalCount"`
+ } `json:"projects"`
+ } `json:"items"`
+}
+
+// webhooksResponse is the response of /v2/webhooks API
+type webhooksResponse struct {
+ Items []struct {
+ ID string `json:"_id"`
+ Name string `json:"name"`
+ Url string `json:"url"`
+ } `json:"items"`
+}
+
+// makeLaunchDarklyRequest send the HTTP GET API request to passed url with passed token and return response body and status code
+func makeLaunchDarklyRequest(client *http.Client, endpoint, token string) ([]byte, int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
+ defer cancel()
+
+ // create request
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+endpoint, http.NoBody)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ // add required keys in the header
+ req.Header.Set("Authorization", token)
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ defer func() {
+ _, _ = io.Copy(io.Discard, resp.Body)
+ _ = resp.Body.Close()
+ }()
+
+ responseBodyByte, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ return responseBodyByte, resp.StatusCode, nil
+}
+
+func CaptureResources(client *http.Client, token string, secretInfo *SecretInfo) error {
+ var (
+ wg sync.WaitGroup
+ errAggWg sync.WaitGroup
+ aggregatedErrs = make([]error, 0)
+ errChan = make(chan error, 1)
+ )
+
+ errAggWg.Add(1)
+ go func() {
+ defer errAggWg.Done()
+ for err := range errChan {
+ aggregatedErrs = append(aggregatedErrs, err)
+ }
+ }()
+
+ // helper to launch tasks concurrently.
+ launchTask := func(task func() error) {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if err := task(); err != nil {
+ errChan <- err
+ }
+ }()
+ }
+
+ // capture top-level resources
+ launchTask(func() error { return captureApplications(client, token, secretInfo) })
+ launchTask(func() error { return captureRepositories(client, token, secretInfo) })
+
+ // capture projects
+ launchTask(func() error {
+ if err := captureProjects(client, token, secretInfo); err != nil {
+ return err
+ }
+
+ // capture project sub resources
+ projects := secretInfo.listResourceByType(projectKey)
+ for _, proj := range projects {
+ launchTask(func() error { return captureProjectFeatureFlags(client, token, proj, secretInfo) })
+ launchTask(func() error { return captureProjectEnv(client, token, proj, secretInfo) })
+ }
+
+ return nil
+ })
+
+ launchTask(func() error { return captureMembers(client, token, secretInfo) })
+ launchTask(func() error { return captureDestinations(client, token, secretInfo) })
+ launchTask(func() error { return captureTemplates(client, token, secretInfo) })
+ launchTask(func() error { return captureTeams(client, token, secretInfo) })
+ launchTask(func() error { return captureWebhooks(client, token, secretInfo) })
+
+ wg.Wait()
+ close(errChan)
+ errAggWg.Wait()
+
+ if len(aggregatedErrs) > 0 {
+ return errors.Join(aggregatedErrs...)
+ }
+
+ return nil
+}
+
+// docs: https://launchdarkly.com/docs/api/applications-beta/get-applications
+func captureApplications(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[applicationKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var applications = applicationsResponse{}
+
+ if err := json.Unmarshal(response, &applications); err != nil {
+ return err
+ }
+
+ for _, application := range applications.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/app/%s", application.Key),
+ Name: application.Name,
+ Type: applicationKey,
+ MetaData: map[string]string{
+ "Maintainer Email": application.Maintainer.Email,
+ "Kind": application.Kind,
+ MetadataKey: application.Key,
+ },
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/code-references/get-repositories
+func captureRepositories(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[repositoryKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var repositories = repositoriesResponse{}
+
+ if err := json.Unmarshal(response, &repositories); err != nil {
+ return err
+ }
+
+ for _, repository := range repositories.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("%s/repo/%s/%d", repository.Type, repository.Name, repository.Version), // no unique id exist, so we make one
+ Name: repository.Name,
+ Type: repositoryKey,
+ MetaData: map[string]string{
+ "Default branch": repository.DefaultBranch,
+ "Version": strconv.Itoa(repository.Version),
+ "Source link": repository.SourceLink,
+ MetadataKey: repositoryKey,
+ },
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/projects/get-projects
+func captureProjects(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[projectKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var projects = projectsResponse{}
+
+ if err := json.Unmarshal(response, &projects); err != nil {
+ return err
+ }
+
+ for _, project := range projects.Items {
+ secretInfo.appendResource(Resource{
+ ID: fmt.Sprintf("launchdarkly/proj/%s", project.ID),
+ Name: project.Name,
+ Type: projectKey,
+ MetaData: map[string]string{
+ MetadataKey: project.Key,
+ },
+ })
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/feature-flags/get-feature-flags
+func captureProjectFeatureFlags(client *http.Client, token string, parent Resource, secretInfo *SecretInfo) error {
+ projectKey, exist := parent.MetaData[MetadataKey]
+ if !exist {
+ return errors.New("project key not found")
+ }
+
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints[featureFlagsKey], projectKey), token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var flags = featureFlagsResponse{}
+
+ if err := json.Unmarshal(response, &flags); err != nil {
+ return err
+ }
+
+ for _, flag := range flags.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/proj/%s/flag/%s", projectKey, flag.Key),
+ Name: flag.Name,
+ Type: featureFlagsKey,
+ MetaData: map[string]string{
+ "Kind": flag.Kind,
+ },
+ ParentResource: &parent,
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/environments/get-environments-by-project
+func captureProjectEnv(client *http.Client, token string, parent Resource, secretInfo *SecretInfo) error {
+ projectKey, exist := parent.MetaData[MetadataKey]
+ if !exist {
+ return errors.New("project key not found")
+ }
+
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints[environmentKey], projectKey), token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var envs = environmentsResponse{}
+
+ if err := json.Unmarshal(response, &envs); err != nil {
+ return err
+ }
+
+ for _, env := range envs.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/%s/env/%s", projectKey, env.ID),
+ Name: env.Name,
+ Type: environmentKey,
+ MetaData: map[string]string{
+ MetadataKey: env.Key,
+ },
+ ParentResource: &parent,
+ }
+
+ secretInfo.appendResource(resource)
+
+ // capture project env child resources
+ if err := captureProjectEnvExperiments(client, token, projectKey, resource, secretInfo); err != nil {
+ return err
+ }
+
+ if err := captureProjectHoldouts(client, token, projectKey, resource, secretInfo); err != nil {
+ return err
+ }
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/experiments/get-experiments
+func captureProjectEnvExperiments(client *http.Client, token string, projectKey string, parent Resource, secretInfo *SecretInfo) error {
+ envKey, exist := parent.MetaData[MetadataKey]
+ if !exist {
+ return errors.New("env key not found")
+ }
+
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints[experimentKey], projectKey, envKey), token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var exps = experimentResponse{}
+
+ if err := json.Unmarshal(response, &exps); err != nil {
+ return err
+ }
+
+ for _, exp := range exps.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/%s/env/%s/exp/%s", projectKey, envKey, exp.ID),
+ Name: exp.Name,
+ Type: experimentKey,
+ MetaData: map[string]string{
+ MetadataKey: exp.Key,
+ "Maintiner ID": exp.MaintainerID,
+ },
+ ParentResource: &parent,
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
+ return nil
+ case http.StatusTooManyRequests:
+ time.Sleep(1 * time.Second)
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/holdouts-beta/get-all-holdouts
+func captureProjectHoldouts(client *http.Client, token string, projectKey string, parent Resource, secretInfo *SecretInfo) error {
+ envKey, exist := parent.MetaData[MetadataKey]
+ if !exist {
+ return errors.New("env key not found")
+ }
+
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints[holdoutsKey], projectKey, envKey), token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var holdouts = holdoutsResponse{}
+
+ if err := json.Unmarshal(response, &holdouts); err != nil {
+ return err
+ }
+
+ for _, holdout := range holdouts.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/%s/env/%s/holdout/%s", projectKey, envKey, holdout.ID),
+ Name: holdout.Name,
+ Type: holdoutsKey,
+ MetaData: map[string]string{
+ "Status": holdout.Status,
+ holdoutsKey: holdout.Key,
+ },
+ ParentResource: &parent,
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/account-members/get-members
+func captureMembers(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[membersKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var members = membersResponse{}
+
+ if err := json.Unmarshal(response, &members); err != nil {
+ return err
+ }
+
+ for _, member := range members.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/member/%s", member.ID),
+ Name: member.FirstName + " " + member.LastName,
+ Type: membersKey,
+ MetaData: map[string]string{
+ "Role": member.Role,
+ "Email": member.Email,
+ },
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/data-export-destinations/get-destinations
+func captureDestinations(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[destinationsKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var destinations = destinationsResponse{}
+
+ if err := json.Unmarshal(response, &destinations); err != nil {
+ return err
+ }
+
+ for _, destination := range destinations.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/destination/%s", destination.ID),
+ Name: destination.Name,
+ Type: destinationsKey,
+ MetaData: map[string]string{
+ "Kind": destination.Kind,
+ "Version": strconv.Itoa(destination.Version),
+ },
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/workflow-templates/get-workflow-templates
+func captureTemplates(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[templatesKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var templates = templatesResponse{}
+
+ if err := json.Unmarshal(response, &templates); err != nil {
+ return err
+ }
+
+ for _, template := range templates.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/templates/%s", template.ID),
+ Name: template.Name,
+ Type: templatesKey,
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/teams/get-teams
+func captureTeams(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[teamsKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var teams = teamsResponse{}
+
+ if err := json.Unmarshal(response, &teams); err != nil {
+ return err
+ }
+
+ for _, team := range teams.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/teams/%s", team.Key),
+ Name: team.Name,
+ Type: teamsKey,
+ MetaData: map[string]string{
+ "Total Roles Count": strconv.Itoa(team.Roles.TotalCount),
+ "Total Memvers Count": strconv.Itoa(team.Members.TotalCount),
+ "Total Projects Count": strconv.Itoa(team.Projects.TotalCount),
+ },
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// docs: https://launchdarkly.com/docs/api/webhooks/get-all-webhooks
+func captureWebhooks(client *http.Client, token string, secretInfo *SecretInfo) error {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints[webhooksKey], token)
+ if err != nil {
+ return err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var webhooks = webhooksResponse{}
+
+ if err := json.Unmarshal(response, &webhooks); err != nil {
+ return err
+ }
+
+ for _, webhook := range webhooks.Items {
+ resource := Resource{
+ ID: fmt.Sprintf("launchdarkly/webhooks/%s", webhook.ID),
+ Name: webhook.Name,
+ Type: webhooksKey,
+ }
+
+ secretInfo.appendResource(resource)
+ }
+
+ return nil
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return nil
+ default:
+ return fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
diff --git a/pkg/analyzer/analyzers/launchdarkly/result_output.json b/pkg/analyzer/analyzers/launchdarkly/result_output.json
new file mode 100644
index 000000000..45e8714cb
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/result_output.json
@@ -0,0 +1,102 @@
+{
+ "AnalyzerType": 6,
+ "Bindings": [
+ {
+ "Resource": {
+ "Name": "Production",
+ "FullyQualifiedName": "launchdarkly/default/env/61543c5956be602355624871",
+ "Type": "Environment",
+ "Metadata": {
+ "key": "production"
+ },
+ "Parent": {
+ "Name": "secretscanner",
+ "FullyQualifiedName": "launchdarkly/proj/61543c5956be60235562486e",
+ "Type": "Project",
+ "Metadata": {
+ "key": "default"
+ },
+ "Parent": null
+ }
+ },
+ "Permission": {
+ "Value": "admin",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "Roxanne Tampus",
+ "FullyQualifiedName": "launchdarkly/member/61543c5956be60235562486f",
+ "Type": "Member",
+ "Metadata": {},
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "admin",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "Test",
+ "FullyQualifiedName": "launchdarkly/default/env/61543c5956be602355624870",
+ "Type": "Environment",
+ "Metadata": {
+ "key": "test"
+ },
+ "Parent": {
+ "Name": "secretscanner",
+ "FullyQualifiedName": "launchdarkly/proj/61543c5956be60235562486e",
+ "Type": "Project",
+ "Metadata": {
+ "key": "default"
+ },
+ "Parent": null
+ }
+ },
+ "Permission": {
+ "Value": "admin",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "secretscanner",
+ "FullyQualifiedName": "launchdarkly/proj/61543c5956be60235562486e",
+ "Type": "Project",
+ "Metadata": {
+ "key": "default"
+ },
+ "Parent": null
+ },
+ "Permission": {
+ "Value": "admin",
+ "Parent": null
+ }
+ },
+ {
+ "Resource": {
+ "Name": "secretscanner",
+ "FullyQualifiedName": "launchdarkly/proj/default/flag/secretscanner",
+ "Type": "Feature Flags",
+ "Metadata": {},
+ "Parent": {
+ "Name": "secretscanner",
+ "FullyQualifiedName": "launchdarkly/proj/61543c5956be60235562486e",
+ "Type": "Project",
+ "Metadata": {
+ "key": "default"
+ },
+ "Parent": null
+ }
+ },
+ "Permission": {
+ "Value": "admin",
+ "Parent": null
+ }
+ }
+ ],
+ "UnboundedResources": null,
+ "Metadata": {}
+}
\ No newline at end of file
diff --git a/pkg/analyzer/analyzers/launchdarkly/user.go b/pkg/analyzer/analyzers/launchdarkly/user.go
new file mode 100644
index 000000000..06c69f320
--- /dev/null
+++ b/pkg/analyzer/analyzers/launchdarkly/user.go
@@ -0,0 +1,230 @@
+/*
+user.go file is all related to calling APIs to get user and token information and formatting them to secretInfo User.
+
+It calls 3 APIs:
+ - /v2/caller-identity
+ - /v2/tokens/<id> (with token id from previous api response)
+ - /v2/roles/<role_id> (if custom role id is present in tokens) (more than one role can be assigned to token as well)
+
+it formats all these responses into one User struct for secretInfo.
+*/
+package launchdarkly
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+)
+
+// callerIdentityResponse is /v2/caller-identity API response
+type callerIdentityResponse struct {
+ AccountID string `json:"accountId"`
+ TokenName string `json:"tokenName"`
+ TokenID string `json:"tokenId"`
+ MemberID string `json:"memberId"`
+ ServiceToken bool `json:"serviceToken"`
+}
+
+// tokenResponse is the /v2/tokens/<id> API response
+type tokenResponse struct {
+ OwnerID string `json:"ownerId"`
+ Member tokenMemberResponse `json:"_member"`
+ Name string `json:"name"`
+ CustomRoleIDs []string `json:"customRoleIds,omitempty"`
+ InlineRole []tokenPolicyResponse `json:"inlineRole,omitempty"`
+ Role string `json:"role"`
+ ServiceToken bool `json:"serviceToken"`
+ DefaultAPIVersion int `json:"defaultApiVersion"`
+}
+
+// _member object in token response
+type tokenMemberResponse struct {
+ FirstName string `json:"firstName"`
+ LastName string `json:"lastName"`
+ Role string `json:"role"`
+ Email string `json:"email"`
+}
+
+// inlineRole object in token response
+type tokenPolicyResponse struct {
+ Effect string `json:"effect,omitempty"`
+ Resources []string `json:"resources,omitempty"`
+ NotResources []string `json:"notResources,omitempty"`
+ Actions []string `json:"actions,omitempty"`
+ NotActions []string `json:"notActions,omitempty"`
+}
+
+// customRoleResponse is the /v2/roles/<role_id> API response
+type customRoleResponse struct {
+ ID string `json:"_id"`
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Policy []tokenPolicyResponse `json:"policy"`
+ BasePermission string `json:"basePermissions"`
+ AssignedTo struct {
+ MembersCount int `json:"membersCount"`
+ TeamsCount int `json:"teamsCount"`
+ } `json:"assignedTo"`
+}
+
+/*
+CaptureUserInformation call following three APIs:
+ - /v2/caller-identity
+ - /v2/tokens/<token_id> (token_id from previous API response)
+ - /v2/roles/<role_id> (roles_id from previous API response if exist)
+
+It format all responses into one secret info User
+*/
+func CaptureUserInformation(client *http.Client, token string, secretInfo *SecretInfo) error {
+ caller, err := getCallerIdentity(client, token)
+ if err != nil {
+ return err
+ }
+
+ tokenDetails, err := getToken(client, caller.TokenID, token)
+ if err != nil {
+ return err
+ }
+
+ customRoles, err := getCustomRole(client, tokenDetails.CustomRoleIDs, token)
+ if err != nil {
+ return err
+ }
+
+ addUserToSecretInfo(caller, tokenDetails, customRoles, secretInfo)
+
+ return nil
+}
+
+// getCallerIdentity call /v2/caller-identity API and return response
+func getCallerIdentity(client *http.Client, token string) (*callerIdentityResponse, error) {
+ response, statusCode, err := makeLaunchDarklyRequest(client, endpoints["callerIdentity"], token)
+ if err != nil {
+ return nil, err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var caller = &callerIdentityResponse{}
+
+ if err := json.Unmarshal(response, caller); err != nil {
+ return caller, err
+ }
+
+ return caller, nil
+ case http.StatusUnauthorized:
+ return nil, errors.New("invalid token; failed to get caller information")
+ default:
+ return nil, fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// getToken call /v2/tokens/<token_id> API and return response
+func getToken(client *http.Client, tokenID, token string) (*tokenResponse, error) {
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints["getToken"], tokenID), token)
+ if err != nil {
+ return nil, err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var token tokenResponse
+
+ if err := json.Unmarshal(response, &token); err != nil {
+ return nil, err
+ }
+
+ return &token, nil
+ case http.StatusUnauthorized:
+ return nil, errors.New("invalid token; failed to get token information")
+ default:
+ return nil, fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+}
+
+// getCustomRole call /v2/roles/<role_id> API for all IDs passed and return list of responses
+func getCustomRole(client *http.Client, customRoleIDs []string, token string) ([]customRoleResponse, error) {
+ var customRoles []customRoleResponse
+
+ for _, customRoleID := range customRoleIDs {
+ response, statusCode, err := makeLaunchDarklyRequest(client, fmt.Sprintf(endpoints["getRole"], customRoleID), token)
+ if err != nil {
+ return nil, err
+ }
+
+ switch statusCode {
+ case http.StatusOK:
+ var customRole customRoleResponse
+
+ if err := json.Unmarshal(response, &customRole); err != nil {
+ return nil, err
+ }
+
+ customRoles = append(customRoles, customRole)
+ case http.StatusUnauthorized:
+ return nil, nil
+ default:
+ return nil, fmt.Errorf("unexpected status code: %d", statusCode)
+ }
+ }
+
+ return customRoles, nil
+}
+
+// makeCallerIdentity take caller, tokenDetails, and customRoles and return secret info CallerIdentity
+func addUserToSecretInfo(caller *callerIdentityResponse, tokenDetails *tokenResponse, customRoles []customRoleResponse, secretInfo *SecretInfo) {
+ user := User{
+ AccountID: caller.AccountID,
+ MemberID: caller.MemberID,
+ Name: tokenDetails.Member.FirstName + " " + tokenDetails.Member.LastName,
+ Role: tokenDetails.Member.Role,
+ Email: tokenDetails.Member.Email,
+ Token: Token{
+ ID: caller.TokenID,
+ Name: tokenDetails.Name,
+ Role: tokenDetails.Role,
+ APIVersion: tokenDetails.DefaultAPIVersion,
+ IsServiceToken: tokenDetails.ServiceToken,
+ InlineRole: toPolicy(tokenDetails.InlineRole),
+ CustomRoles: toCustomRoles(customRoles),
+ },
+ }
+
+ secretInfo.User = user
+}
+
+// toPolicy convert inlinePolicy from token response to secret info caller identity policy
+func toPolicy(inlinePolices []tokenPolicyResponse) []Policy {
+ var policies = make([]Policy, 0)
+
+ for _, inlinePolicy := range inlinePolices {
+ policies = append(policies, Policy{
+ Resources: inlinePolicy.Resources,
+ NotResources: inlinePolicy.NotResources,
+ Actions: inlinePolicy.Actions,
+ NotActions: inlinePolicy.NotActions,
+ Effect: inlinePolicy.Effect,
+ })
+ }
+
+ return policies
+}
+
+// toCustomRoles convert customRole from token response to secret info caller identity custom role
+func toCustomRoles(roles []customRoleResponse) []CustomRole {
+ var customRoles = make([]CustomRole, 0)
+ for _, role := range roles {
+ customRoles = append(customRoles, CustomRole{
+ ID: role.ID,
+ Key: role.Key,
+ Name: role.Name,
+ Polices: toPolicy(role.Policy),
+ BasePermission: role.BasePermission,
+ AssignedToMembers: role.AssignedTo.MembersCount,
+ AssignedToTeams: role.AssignedTo.TeamsCount,
+ })
+ }
+
+ return customRoles
+}
diff --git a/pkg/analyzer/cli.go b/pkg/analyzer/cli.go
index 8d87e1fe2..5882abba8 100644
--- a/pkg/analyzer/cli.go
+++ b/pkg/analyzer/cli.go
@@ -18,6 +18,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/gitlab"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/groq"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/huggingface"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/launchdarkly"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/mailchimp"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/mailgun"
"github.com/trufflesecurity/trufflehog/v3/pkg/analyzer/analyzers/mysql"
@@ -112,5 +113,7 @@ func Run(keyType string, secretInfo SecretInfo) {
airtablepat.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
case "groq":
groq.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
+ case "launchdarkly":
+ launchdarkly.AnalyzeAndPrintPermissions(secretInfo.Cfg, secretInfo.Parts["key"])
}
}
diff --git a/pkg/detectors/launchdarkly/launchdarkly.go b/pkg/detectors/launchdarkly/launchdarkly.go
index 0de008fd3..c101264a5 100644
--- a/pkg/detectors/launchdarkly/launchdarkly.go
+++ b/pkg/detectors/launchdarkly/launchdarkly.go
@@ -101,6 +101,11 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}
}
}
+
+ s1.AnalysisInfo = map[string]string{
+ "key": resMatch,
+ }
+
} else if res.StatusCode == 401 {
// 401 is expected for an invalid token, so there is nothing to do here.
} else {