Enable errcheck and staticcheck for golangci-lint v2 and resolve all issues (#4924)

* enable errcheck and staticcheck for golangci-lint v2 and resolve all issues

* skip lint on intentional reference of deprecated DetectorType values
This commit is contained in:
Amaan Ullah
2026-05-15 17:07:14 +05:00
committed by GitHub
parent 3a022f9d59
commit 0fa069c12f
801 changed files with 1827 additions and 1537 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
with: with:
# NOTE: Version and args must match scripts/lint.sh # NOTE: Version and args must match scripts/lint.sh
version: v2.11.4 version: v2.11.4
args: --disable errcheck,staticcheck --enable bodyclose,copyloopvar,misspell --timeout 10m args: --enable bodyclose,copyloopvar,misspell --timeout 10m
man-page-staleness: man-page-staleness:
name: man-page-staleness name: man-page-staleness
runs-on: ubuntu-latest runs-on: ubuntu-latest
+3 -3
View File
@@ -33,9 +33,9 @@ func main() {
flag.BoolVar(&failOnFindings, "fail", false, "exit 1 if any findings are reported (default: warning-only)") flag.BoolVar(&failOnFindings, "fail", false, "exit 1 if any findings are reported (default: warning-only)")
flag.BoolVar(&quiet, "quiet", false, "suppress the summary line when no findings are reported") flag.BoolVar(&quiet, "quiet", false, "suppress the summary line when no findings are reported")
flag.Usage = func() { flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] [dir ...]\n", os.Args[0]) _, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] [dir ...]\n", os.Args[0])
fmt.Fprintln(flag.CommandLine.Output(), "\nFinds detector packages that construct detectors.Result without setting SecretParts.") _, _ = fmt.Fprintln(flag.CommandLine.Output(), "\nFinds detector packages that construct detectors.Result without setting SecretParts.")
fmt.Fprintln(flag.CommandLine.Output(), "\nFlags:") _, _ = fmt.Fprintln(flag.CommandLine.Output(), "\nFlags:")
flag.PrintDefaults() flag.PrintDefaults()
} }
flag.Parse() flag.Parse()
+1 -1
View File
@@ -219,7 +219,7 @@ func main() {
logFatal(err, "error scanning repo") logFatal(err, "error scanning repo")
} }
logger.Info("scanned repo", "repo", r) logger.Info("scanned repo", "repo", r)
defer os.RemoveAll(path) defer func() { _ = os.RemoveAll(path) }()
}(repo) }(repo)
} }
+2 -2
View File
@@ -465,7 +465,7 @@ func run(state overseer.State, logSync func() error) {
if *githubScanToken != "" { if *githubScanToken != "" {
// NOTE: this kludge is here to do an authenticated shallow commit // NOTE: this kludge is here to do an authenticated shallow commit
// TODO: refactor to better pass credentials // TODO: refactor to better pass credentials
os.Setenv("GITHUB_TOKEN", *githubScanToken) _ = os.Setenv("GITHUB_TOKEN", *githubScanToken)
} }
if *concurrency <= 0 { if *concurrency <= 0 {
@@ -725,7 +725,7 @@ func runSingleScan(ctx context.Context, cmd string, cfg engine.Config) (metrics,
handleFinishedMetrics := func(ctx context.Context, finishedMetrics <-chan sources.UnitMetrics, jobReportWriter io.WriteCloser) { handleFinishedMetrics := func(ctx context.Context, finishedMetrics <-chan sources.UnitMetrics, jobReportWriter io.WriteCloser) {
go func() { go func() {
defer func() { defer func() {
jobReportWriter.Close() _ = jobReportWriter.Close()
if namer, ok := jobReportWriter.(interface{ Name() string }); ok { if namer, ok := jobReportWriter.(interface{ Name() string }); ok {
ctx.Logger().Info("report written", "path", namer.Name()) ctx.Logger().Info("report written", "path", namer.Name())
} else { } else {
+3 -4
View File
@@ -25,8 +25,7 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeAir
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
info, err := AnalyzePermissions(a.Cfg, credInfo["key"]) info, err := AnalyzePermissions(a.Cfg, credInfo["key"])
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -109,7 +108,7 @@ func validateKey(cfg *config.Config, key string) (bool, []Project, error) {
} }
// read response // read response
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// if status code is 200, decode response // if status code is 200, decode response
if resp.StatusCode == 200 { if resp.StatusCode == 200 {
@@ -150,7 +149,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
return nil, err return nil, err
} }
if !valid { if !valid {
return nil, fmt.Errorf("Invalid Airbrake User API Key") return nil, fmt.Errorf("invalid Airbrake User API Key")
} }
info := &SecretInfo{ info := &SecretInfo{
@@ -119,7 +119,7 @@ func determineScope(token string, perm common.Permission, requiredIDs map[string
if requiredIDs != nil { if requiredIDs != nil {
for _, key := range endpoint.RequiredIDs { for _, key := range endpoint.RequiredIDs {
if value, ok := requiredIDs[key]; ok { if value, ok := requiredIDs[key]; ok {
url = strings.Replace(url, fmt.Sprintf("{%s}", key), value, -1) url = strings.ReplaceAll(url, fmt.Sprintf("{%s}", key), value)
} }
} }
} }
@@ -128,7 +128,7 @@ func determineScope(token string, perm common.Permission, requiredIDs map[string
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == endpoint.ExpectedSuccessStatus { if resp.StatusCode == endpoint.ExpectedSuccessStatus {
scopeStatusMap[scopeString] = true scopeStatusMap[scopeString] = true
@@ -18,12 +18,12 @@ func fetchAirtableRecords(token string, baseID string, tableID string) ([]common
if !exists { if !exists {
return nil, fmt.Errorf("endpoint for ListRecordsEndpoint does not exist") return nil, fmt.Errorf("endpoint for ListRecordsEndpoint does not exist")
} }
url := strings.Replace(strings.Replace(endpoint.URL, "{baseID}", baseID, -1), "{tableID}", tableID, -1) url := strings.ReplaceAll(strings.ReplaceAll(endpoint.URL, "{baseID}", baseID), "{tableID}", tableID)
resp, err := common.CallAirtableAPI(token, "GET", url) resp, err := common.CallAirtableAPI(token, "GET", url)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch Airtable records, status: %d", resp.StatusCode) return nil, fmt.Errorf("failed to fetch Airtable records, status: %d", resp.StatusCode)
@@ -39,7 +39,7 @@ func FetchAirtableUserInfo(token string) (*AirtableUserInfo, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch Airtable user info, status: %d", resp.StatusCode) return nil, fmt.Errorf("failed to fetch Airtable user info, status: %d", resp.StatusCode)
@@ -62,7 +62,7 @@ func FetchAirtableBases(token string) (*AirtableBases, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch Airtable bases, status: %d", resp.StatusCode) return nil, fmt.Errorf("failed to fetch Airtable bases, status: %d", resp.StatusCode)
@@ -96,7 +96,7 @@ func fetchBaseSchema(token string, baseID string) (*Schema, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch schema for base %s, status: %d", baseID, resp.StatusCode) return nil, fmt.Errorf("failed to fetch schema for base %s, status: %d", baseID, resp.StatusCode)
+1 -1
View File
@@ -227,7 +227,7 @@ func (h *HttpStatusTest) RunTest(headers map[string]string) error {
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
+3 -3
View File
@@ -116,10 +116,10 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
return nil, fmt.Errorf("Invalid Asana API Key") return nil, fmt.Errorf("invalid Asana API Key")
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&me) err = json.NewDecoder(resp.Body).Decode(&me)
if err != nil { if err != nil {
@@ -127,7 +127,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
} }
if me.Data.Email == "" { if me.Data.Email == "" {
return nil, fmt.Errorf("Invalid Asana API Key") return nil, fmt.Errorf("invalid Asana API Key")
} }
return &me, nil return &me, nil
} }
@@ -146,7 +146,7 @@ func getScopesAndType(cfg *config.Config, key string) (string, []string, error)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// parse response headers // parse response headers
credentialType := resp.Header.Get("x-credential-type") credentialType := resp.Header.Get("x-credential-type")
@@ -198,7 +198,7 @@ func getRepositories(cfg *config.Config, key string, role string) (RepoJSON, err
if err != nil { if err != nil {
return repos, err return repos, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// parse response body // parse response body
err = json.NewDecoder(resp.Body).Decode(&repos) err = json.NewDecoder(resp.Body).Decode(&repos)
+1 -1
View File
@@ -107,7 +107,7 @@ func (r LoggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error
if err != nil { if err != nil {
return resp, fmt.Errorf("failed to open log file: %w", err) return resp, fmt.Errorf("failed to open log file: %w", err)
} }
defer file.Close() defer func() { _ = file.Close() }()
// Write log entry to file. // Write log entry to file.
if _, err := file.WriteString(logEntry); err != nil { if _, err := file.WriteString(logEntry); err != nil {
+1 -1
View File
@@ -216,7 +216,7 @@ func ValidateApiKey(client *http.Client, baseURL, apiKey string) (bool, error) {
case http.StatusForbidden: case http.StatusForbidden:
return false, nil return false, nil
default: default:
return false, fmt.Errorf("Unable to validate api key with status code: %d", resp.StatusCode) return false, fmt.Errorf("unable to validate api key with status code: %d", resp.StatusCode)
} }
} }
@@ -34,13 +34,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeDig
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -125,7 +123,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, headers map[string]string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -232,7 +230,7 @@ func getUser(cfg *config.Config, token string) (*user, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -86,14 +86,12 @@ func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analy
// check if the `key` exist in the credentials info // check if the `key` exist in the credentials info
key, exist := credInfo["key"] key, exist := credInfo["key"]
if !exist { if !exist {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("key not found in credentials info"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("key not found in credentials info"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
@@ -242,9 +240,10 @@ func fetchUser(client *http.Client, key string) (*User, error) {
return nil, err return nil, err
} }
if errorResp.Detail.Status == InvalidAPIKey || errorResp.Detail.Status == NotVerifiable { switch errorResp.Detail.Status {
case InvalidAPIKey, NotVerifiable:
return nil, errors.New("invalid api key") return nil, errors.New("invalid api key")
} else if errorResp.Detail.Status == MissingPermissions { case MissingPermissions:
// key is missing user read permissions but is valid // key is missing user read permissions but is valid
return nil, nil return nil, nil
} }
+1 -1
View File
@@ -83,7 +83,7 @@ func AnalyzePermissions(cfg *config.Config, token string) (*secretInfo, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -78,7 +78,7 @@ func permissionFormatter(key, val any) (string, string) {
if perm, ok := val.(Permission); ok { if perm, ok := val.(Permission); ok {
permStr, err := perm.ToString() permStr, err := perm.ToString()
if err != nil { if err != nil {
log.Fatal(fmt.Errorf("Error converting permission to string: %v", err)) log.Fatal(fmt.Errorf("error converting permission to string: %v", err))
} }
var permissionStr string var permissionStr string
switch { switch {
@@ -217,7 +217,7 @@ func getCodeScanningAlertsPermission(client *gh.Client, repo *gh.Repository, cur
// Risk: Extremely Low // Risk: Extremely Low
// -> GET request to /repos/{owner}/{repo}/code-scanning/alerts // -> GET request to /repos/{owner}/{repo}/code-scanning/alerts
_, resp, err := client.CodeScanning.ListAlertsForRepo(context.Background(), *repo.Owner.Login, *repo.Name, nil) _, resp, err := client.CodeScanning.ListAlertsForRepo(context.Background(), *repo.Owner.Login, *repo.Name, nil)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch { switch {
case resp.StatusCode == 403: case resp.StatusCode == 403:
@@ -427,7 +427,7 @@ func getDependabotAlertsPermission(client *gh.Client, repo *gh.Repository, curre
// Risk: Extremely Low // Risk: Extremely Low
// GET /repos/{owner}/{repo}/dependabot/alerts // GET /repos/{owner}/{repo}/dependabot/alerts
_, resp, err := client.Dependabot.ListRepoAlerts(context.Background(), *repo.Owner.Login, *repo.Name, &gh.ListAlertsOptions{}) _, resp, err := client.Dependabot.ListRepoAlerts(context.Background(), *repo.Owner.Login, *repo.Name, &gh.ListAlertsOptions{})
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case 403: case 403:
+6 -6
View File
@@ -155,7 +155,7 @@ func getPersonalAccessToken(cfg *config.Config, key, host string) (AccessTokenJS
return tokens, resp.StatusCode, err return tokens, resp.StatusCode, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil { if err := json.NewDecoder(resp.Body).Decode(&tokens); err != nil {
return tokens, resp.StatusCode, err return tokens, resp.StatusCode, err
} }
@@ -183,7 +183,7 @@ func getAccessibleProjects(cfg *config.Config, key, host string) ([]ProjectsJSON
return projects, err return projects, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
bodyBytes, err := io.ReadAll(resp.Body) bodyBytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
@@ -197,7 +197,7 @@ func getAccessibleProjects(cfg *config.Config, key, host string) ([]ProjectsJSON
if err := json.NewDecoder(newBody()).Decode(&projects); err != nil { if err := json.NewDecoder(newBody()).Decode(&projects); err != nil {
var e ErrorJSON var e ErrorJSON
if err := json.NewDecoder(newBody()).Decode(&e); err == nil { if err := json.NewDecoder(newBody()).Decode(&e); err == nil {
return projects, fmt.Errorf("Insufficient Scope to query for projects. We need api or read_api permissions.") return projects, errors.New("insufficient scope to query for projects: we need api or read_api permissions")
} }
return projects, err return projects, err
} }
@@ -219,7 +219,7 @@ func getMetadata(cfg *config.Config, key, host string) (MetadataJSON, error) {
return metadata, err return metadata, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
bodyBytes, err := io.ReadAll(resp.Body) bodyBytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
@@ -239,7 +239,7 @@ func getMetadata(cfg *config.Config, key, host string) (MetadataJSON, error) {
if err := json.NewDecoder(newBody()).Decode(&e); err != nil { if err := json.NewDecoder(newBody()).Decode(&e); err != nil {
return metadata, err return metadata, err
} }
return metadata, fmt.Errorf("Insufficient Scope to query for metadata. We need read_user, ai_features, api or read_api permissions.") return metadata, errors.New("insufficient scope to query for metadata: we need read_user, ai_features, api or read_api permissions")
} }
return metadata, nil return metadata, nil
@@ -258,7 +258,7 @@ func AnalyzePermissions(cfg *config.Config, key string, host string) (*SecretInf
return nil, err return nil, err
} }
if statusCode != http.StatusOK { if statusCode != http.StatusOK {
return nil, fmt.Errorf("Invalid GitLab Access Token") return nil, errors.New("invalid GitLab access token")
} }
meta, err := getMetadata(cfg, key, host) meta, err := getMetadata(cfg, key, host)
@@ -33,14 +33,12 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeHug
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok || key == "" { if !ok || key == "" {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("key not found in credentialInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("key not found in credentialInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -99,15 +97,17 @@ func bakefineGrainedBindings(allModels []Model, tokenJSON HFTokenJSON) []analyze
Value: string(analyzers.NONE), Value: string(analyzers.NONE),
} }
for _, perm := range permission.Permissions { for _, perm := range permission.Permissions {
if perm == "repo.content.read" { switch perm {
case "repo.content.read":
privs.Value = string(analyzers.READ) privs.Value = string(analyzers.READ)
} else if perm == "repo.write" { case "repo.write":
privs.Value = string(analyzers.WRITE) privs.Value = string(analyzers.WRITE)
} }
} }
if permission.Entity.Type == "user" || permission.Entity.Type == "org" { switch permission.Entity.Type {
case "user", "org":
nameToPermissions[permission.Entity.Name] = privs nameToPermissions[permission.Entity.Name] = privs
} else if permission.Entity.Type == "model" { case "model":
nameToPermissions[modelNameLookup(allModels, permission.Entity.ID)] = privs nameToPermissions[modelNameLookup(allModels, permission.Entity.ID)] = privs
} }
} }
@@ -334,7 +334,7 @@ func getModelsByAuthor(cfg *config.Config, key string, author string) ([]Model,
} }
// defer the response body closing // defer the response body closing
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// read response // read response
if err := json.NewDecoder(resp.Body).Decode(&modelsJSON); err != nil { if err := json.NewDecoder(resp.Body).Decode(&modelsJSON); err != nil {
@@ -370,7 +370,7 @@ func getTokenInfo(cfg *config.Config, key string) (HFTokenJSON, bool, error) {
} }
// defer the response body closing // defer the response body closing
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// read response // read response
if err := json.NewDecoder(resp.Body).Decode(&tokenJSON); err != nil { if err := json.NewDecoder(resp.Body).Decode(&tokenJSON); err != nil {
@@ -392,7 +392,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
} }
if !success { if !success {
return nil, fmt.Errorf("Invalid HuggingFace Access Token") return nil, fmt.Errorf("invalid HuggingFace Access Token")
} }
// get all models by username // get all models by username
@@ -609,15 +609,17 @@ func printAccessibleModels(allModels []Model, tokenJSON HFTokenJSON) {
read := false read := false
write := false write := false
for _, perm := range permission.Permissions { for _, perm := range permission.Permissions {
if perm == "repo.content.read" { switch perm {
case "repo.content.read":
read = true read = true
} else if perm == "repo.write" { case "repo.write":
write = true write = true
} }
} }
if permission.Entity.Type == "user" || permission.Entity.Type == "org" { switch permission.Entity.Type {
case "user", "org":
nameToPermissions[permission.Entity.Name] = Permissions{Read: read, Write: write} nameToPermissions[permission.Entity.Name] = Permissions{Read: read, Write: write}
} else if permission.Entity.Type == "model" { case "model":
nameToPermissions[modelNameLookup(allModels, permission.Entity.ID)] = Permissions{Read: read, Write: write} nameToPermissions[modelNameLookup(allModels, permission.Entity.ID)] = Permissions{Read: read, Write: write}
} }
} }
+4 -5
View File
@@ -428,13 +428,12 @@ func captureAuditLogs(client *http.Client, domain, email, token string, secretIn
} }
func handleStatusCode(statusCode int, endpoint string) error { func handleStatusCode(statusCode int, endpoint string) error {
switch { switch statusCode {
case statusCode == http.StatusOK: case http.StatusOK:
return nil return nil
case statusCode == http.StatusBadRequest: case http.StatusBadRequest:
return fmt.Errorf("bad request for API: %s", endpoint) return fmt.Errorf("bad request for API: %s", endpoint)
case statusCode == http.StatusUnauthorized, statusCode == http.StatusForbidden, case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusConflict:
statusCode == http.StatusNotFound, statusCode == http.StatusConflict:
return nil return nil
default: default:
return fmt.Errorf("unexpected status code: %d for API: %s", statusCode, endpoint) return fmt.Errorf("unexpected status code: %d for API: %s", statusCode, endpoint)
@@ -146,7 +146,7 @@ func getMetadata(cfg *config.Config, key string) (MetadataJSON, error) {
return metadata, err return metadata, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil { if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {
return metadata, err return metadata, err
@@ -177,7 +177,7 @@ func getDomains(cfg *config.Config, key string) (DomainsJSON, error) {
return domains, err return domains, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if err := json.NewDecoder(resp.Body).Decode(&domains); err != nil { if err := json.NewDecoder(resp.Body).Decode(&domains); err != nil {
return domains, err return domains, err
@@ -198,7 +198,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
return nil, err return nil, err
} }
if metadata.AccountID == "" { if metadata.AccountID == "" {
return nil, fmt.Errorf("Invalid Mailchimp API key") return nil, fmt.Errorf("invalid Mailchimp API key")
} }
// get sending domains // get sending domains
+2 -2
View File
@@ -53,7 +53,7 @@ func getDomains(client *http.Client, apiKey string, secretInfo *SecretInfo) erro
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
return fmt.Errorf("invalid Mailgun API key") return fmt.Errorf("invalid Mailgun API key")
@@ -83,7 +83,7 @@ func getKeys(client *http.Client, apiKey string, secretInfo *SecretInfo) error {
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
return fmt.Errorf("invalid Mailgun API key") return fmt.Errorf("invalid Mailgun API key")
+3 -2
View File
@@ -56,9 +56,10 @@ func (info *secretInfo) addPermission(resourceType ResourceType, permission stri
return return
} }
if permission == "read" { switch permission {
case "read":
info.Permissions[resourceType] = Read info.Permissions[resourceType] = Read
} else if permission == "write" { case "write":
info.Permissions[resourceType] = FullAccess info.Permissions[resourceType] = FullAccess
} }
} }
+6 -6
View File
@@ -292,7 +292,7 @@ func AnalyzePermissions(cfg *config.Config, connectionStr string) (*SecretInfo,
if err != nil { if err != nil {
return nil, fmt.Errorf("connecting to the MySQL database: %w", err) return nil, fmt.Errorf("connecting to the MySQL database: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
// Get the current user // Get the current user
user, err := getUser(db) user, err := getUser(db)
@@ -434,7 +434,7 @@ func getDatabases(db *sql.DB, databases map[string]*Database) error {
if err != nil { if err != nil {
return err return err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
for rows.Next() { for rows.Next() {
var dbName string var dbName string
@@ -462,7 +462,7 @@ func getTables(db *sql.DB, databases map[string]*Database) error {
if err != nil { if err != nil {
return err return err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
for rows.Next() { for rows.Next() {
var dbName string var dbName string
@@ -486,7 +486,7 @@ func getRoutines(db *sql.DB, databases map[string]*Database) error {
if err != nil { if err != nil {
return err return err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
for rows.Next() { for rows.Next() {
var dbName string var dbName string
@@ -513,7 +513,7 @@ func getGrants(db *sql.DB) ([]string, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
var grants []string var grants []string
for rows.Next() { for rows.Next() {
@@ -568,7 +568,7 @@ func processGrant(grant string, databases map[string]*Database, globalPrivs *Glo
// Split on " ON " // Split on " ON "
parts := strings.Split(grant, " ON ") parts := strings.Split(grant, " ON ")
if len(parts) < 2 { if len(parts) < 2 {
return fmt.Errorf("Error processing grant: %s", grant) return fmt.Errorf("error processing grant: %s", grant)
} }
// Put privs in a slice // Put privs in a slice
+5 -7
View File
@@ -30,13 +30,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeNot
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -143,7 +141,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, headers map[string]string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -330,7 +328,7 @@ func getBotInfo(client *http.Client, key string) (*bot, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -368,7 +366,7 @@ func getWorkspaceUsers(client *http.Client, key string) ([]user, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
+2 -3
View File
@@ -31,8 +31,7 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeOpe
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
info, err := AnalyzePermissions(a.Cfg, credInfo["key"]) info, err := AnalyzePermissions(a.Cfg, credInfo["key"])
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -214,7 +213,7 @@ func openAIRequest(cfg *config.Config, method string, url string, key string, da
return nil, nil, err return nil, nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
outBody, err := io.ReadAll(resp.Body) outBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
+4 -6
View File
@@ -30,13 +30,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeOps
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -159,7 +157,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, headers map[string]string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -231,7 +229,7 @@ func getUserList(cfg *config.Config, key string) ([]User, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Decode response body // Decode response body
var userList UsersJSON var userList UsersJSON
+1 -1
View File
@@ -108,7 +108,7 @@ func getPlaidAccounts(client *http.Client, clientID string, secret string, acces
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("received non-OK HTTP status: %d", resp.StatusCode) return nil, fmt.Errorf("received non-OK HTTP status: %d", resp.StatusCode)
@@ -137,7 +137,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, headers map[string]string,
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -539,7 +539,7 @@ func sendGetRequest(cfg *config.Config, id, key, url string, responseObj interfa
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch resp.StatusCode { switch resp.StatusCode {
+8 -8
View File
@@ -278,7 +278,7 @@ func AnalyzePermissions(cfg *config.Config, connectionStr string) (*SecretInfo,
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to connect to Postgres database: %w", err) return nil, fmt.Errorf("failed to connect to Postgres database: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
role, privs, err := getUserPrivs(db) role, privs, err := getUserPrivs(db)
if err != nil { if err != nil {
@@ -372,7 +372,7 @@ func getUserPrivs(db *sql.DB) (string, map[string]bool, error) {
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
var roleName string var roleName string
var isSuperuser, canInherit, canCreateRole, canCreateDB, canLogin, isReplicationRole, bypassesRLS bool var isSuperuser, canInherit, canCreateRole, canCreateDB, canLogin, isReplicationRole, bypassesRLS bool
@@ -389,7 +389,7 @@ func getUserPrivs(db *sql.DB) (string, map[string]bool, error) {
} }
// Map roles to privileges // Map roles to privileges
var mapRoles map[string]bool = map[string]bool{ var mapRoles = map[string]bool{
"Superuser": isSuperuser, "Superuser": isSuperuser,
"Inheritance of Privs": canInherit, "Inheritance of Privs": canInherit,
"Create Role": canCreateRole, "Create Role": canCreateRole,
@@ -427,7 +427,7 @@ func getDBPrivs(db *sql.DB) (string, []DB, error) {
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
dbs := make([]DB, 0) dbs := make([]DB, 0)
@@ -501,7 +501,7 @@ func getDBWriter(db DB, current_user string) func(a ...interface{}) string {
func buildSliceDBNames(dbs []DB) []string { func buildSliceDBNames(dbs []DB) []string {
var dbNames []string var dbNames []string
for _, db := range dbs { for _, db := range dbs {
if db.DBPrivs.Connect { if db.Connect {
dbNames = append(dbNames, db.DatabaseName) dbNames = append(dbNames, db.DatabaseName)
} }
} }
@@ -519,7 +519,7 @@ func getTablePrivs(params map[string]string, databases []string) (map[string]map
// color.Red("[x] Failed to connect to Postgres database: %s", dbase) // color.Red("[x] Failed to connect to Postgres database: %s", dbase)
continue continue
} }
defer db.Close() defer func() { _ = db.Close() }()
// Get table privs // Get table privs
query := ` query := `
@@ -543,7 +543,7 @@ func getTablePrivs(params map[string]string, databases []string) (map[string]map
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer func() { _ = rows.Close() }()
// Iterate through the result set // Iterate through the result set
for rows.Next() { for rows.Next() {
@@ -589,7 +589,7 @@ func getTablePrivs(params map[string]string, databases []string) (map[string]map
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, err return nil, err
} }
db.Close() _ = db.Close()
} }
return tablePrivileges, nil return tablePrivileges, nil
+6 -8
View File
@@ -37,13 +37,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypePos
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", errors.New("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -166,7 +164,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, client *http.Client, domain
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -302,7 +300,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
// we need to determine if the key is for US or EU domain // we need to determine if the key is for US or EU domain
domain, user, err := resolveDomainAndUser(cfg, client, key) domain, user, err := resolveDomainAndUser(cfg, client, key)
if err != nil { if err != nil {
return nil, fmt.Errorf("Invalid API Key: %w", err) return nil, fmt.Errorf("invalid API key: %w", err)
} }
info.user = user info.user = user
@@ -439,7 +437,7 @@ func resolveDomainAndUser(cfg *config.Config, client *http.Client, key string) (
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -476,7 +474,7 @@ func getOrganization(cfg *config.Config, client *http.Client, domain string, key
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
+5 -7
View File
@@ -26,13 +26,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypePos
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -148,7 +146,7 @@ func getUserInfo(cfg *config.Config, key string) (UserInfoJSON, error) {
} }
// read response // read response
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// if status code is 200, decode response // if status code is 200, decode response
if resp.StatusCode == 200 { if resp.StatusCode == 200 {
@@ -175,7 +173,7 @@ func getWorkspaces(cfg *config.Config, key string) (WorkspaceJSON, error) {
} }
// read response // read response
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// if status code is 200, decode response // if status code is 200, decode response
if resp.StatusCode == 200 { if resp.StatusCode == 200 {
@@ -224,7 +222,7 @@ func AnalyzePermissions(cfg *config.Config, key string) (*SecretInfo, error) {
} }
if me.User.Username == "" { if me.User.Username == "" {
return nil, fmt.Errorf("Invalid Postman API Key") return nil, fmt.Errorf("invalid Postman API Key")
} }
// get workspaces, if there is error user with empty workspaces will be returned // get workspaces, if there is error user with empty workspaces will be returned
+2 -2
View File
@@ -213,7 +213,7 @@ func getShopInfo(cfg *config.Config, key string, store string) (ShopInfoJSON, er
return shopInfo, err return shopInfo, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&shopInfo) err = json.NewDecoder(resp.Body).Decode(&shopInfo)
if err != nil { if err != nil {
@@ -252,7 +252,7 @@ func getAccessScopes(cfg *config.Config, key string, store string) (AccessScopes
return accessScopes, resp.StatusCode, err return accessScopes, resp.StatusCode, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&accessScopes) err = json.NewDecoder(resp.Body).Decode(&accessScopes)
if err != nil { if err != nil {
+1 -1
View File
@@ -141,7 +141,7 @@ func getSlackOAuthScopes(cfg *config.Config, key string) (scopes string, userDat
if err != nil { if err != nil {
return scopes, userData, err return scopes, userData, err
} }
defer resp.Body.Close() // Close the response body when the function returns defer func() { _ = resp.Body.Close() }() // Close the response body when the function returns
// print body // print body
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
@@ -26,13 +26,11 @@ func (Analyzer) Type() analyzers.AnalyzerType { return analyzers.AnalyzerTypeSou
func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) { func (a Analyzer) Analyze(_ context.Context, credInfo map[string]string) (*analyzers.AnalyzerResult, error) {
key, ok := credInfo["key"] key, ok := credInfo["key"]
if !ok { if !ok {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("missing key in credInfo"), return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationValidateCredentials, analyzers.ServiceConfig, "", fmt.Errorf("missing key in credInfo"))
)
} }
info, err := AnalyzePermissions(a.Cfg, key) info, err := AnalyzePermissions(a.Cfg, key)
if err != nil { if err != nil {
return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err, return nil, analyzers.NewAnalysisError(a.Type().String(), analyzers.OperationAnalyzePermissions, analyzers.ServiceAPI, "", err)
)
} }
return secretInfoToAnalyzerResult(info), nil return secretInfoToAnalyzerResult(info), nil
} }
@@ -116,7 +114,7 @@ func getUserInfo(cfg *config.Config, key string) (UserInfoJSON, error) {
return userInfo, err return userInfo, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&userInfo) err = json.NewDecoder(resp.Body).Decode(&userInfo)
if err != nil { if err != nil {
@@ -151,7 +149,7 @@ func checkSiteAdmin(cfg *config.Config, key string) (bool, error) {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
var response GraphQLResponse var response GraphQLResponse
+2 -2
View File
@@ -173,7 +173,7 @@ func getPermissions(cfg *config.Config, key string) (PermissionsJSON, error) {
return permissions, nil return permissions, nil
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&permissions) err = json.NewDecoder(resp.Body).Decode(&permissions)
if err != nil { if err != nil {
@@ -210,7 +210,7 @@ func getUsers(cfg *config.Config, key string) (TeamJSON, error) {
return team, nil return team, nil
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
err = json.NewDecoder(resp.Body).Decode(&team) err = json.NewDecoder(resp.Body).Decode(&team)
if err != nil { if err != nil {
+9 -7
View File
@@ -162,7 +162,7 @@ func (h *HttpStatusTest) RunTest(cfg *config.Config, headers map[string]string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status code // Check response status code
switch { switch {
@@ -195,7 +195,7 @@ func checkKeyType(key string) (string, error) {
} else if strings.HasPrefix(key, RESTRICTED_PREFIX) { } else if strings.HasPrefix(key, RESTRICTED_PREFIX) {
return RESTRICTED, nil return RESTRICTED, nil
} }
return "", errors.New("Invalid Stripe key format") return "", errors.New("invalid Stripe key format")
} }
func checkKeyEnv(key string) (string, error) { func checkKeyEnv(key string) (string, error) {
@@ -226,7 +226,7 @@ func checkValidity(cfg *config.Config, key string) (bool, error) {
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check the response. Valid is 200 (secret/restricted) or 403 (restricted) // Check the response. Valid is 200 (secret/restricted) or 403 (restricted)
if resp.StatusCode == 200 || resp.StatusCode == 403 { if resp.StatusCode == 200 || resp.StatusCode == 403 {
@@ -290,15 +290,17 @@ func AnalyzeAndPrintPermissions(cfg *config.Config, key string) {
color.Green("[!] Valid Stripe API Key\n\n") color.Green("[!] Valid Stripe API Key\n\n")
if info.KeyType == SECRET { switch info.KeyType {
case SECRET:
color.Green("[i] Key Type: %s", info.KeyType) color.Green("[i] Key Type: %s", info.KeyType)
} else if info.KeyType == RESTRICTED { case RESTRICTED:
color.Yellow("[i] Key Type: %s", info.KeyType) color.Yellow("[i] Key Type: %s", info.KeyType)
} }
if info.KeyEnv == LIVE { switch info.KeyEnv {
case LIVE:
color.Green("[i] Key Environment: %s", info.KeyEnv) color.Green("[i] Key Environment: %s", info.KeyEnv)
} else if info.KeyEnv == TEST { case TEST:
color.Red("[i] Key Environment: %s", info.KeyEnv) color.Red("[i] Key Environment: %s", info.KeyEnv)
} }
+9 -7
View File
@@ -49,7 +49,8 @@ func (a *Analyzer) Analyze(ctx context.Context, credentialInfo map[string]string
} }
var permissions []Permission var permissions []Permission
if info.AccountStatusCode == 200 { switch info.AccountStatusCode {
case 200:
permissions = []Permission{ permissions = []Permission{
AccountManagementRead, AccountManagementRead,
AccountManagementWrite, AccountManagementWrite,
@@ -68,7 +69,7 @@ func (a *Analyzer) Analyze(ctx context.Context, credentialInfo map[string]string
CallManagementRead, CallManagementRead,
CallManagementWrite, CallManagementWrite,
} }
} else if info.AccountStatusCode == 401 { case 401:
permissions = []Permission{ permissions = []Permission{
ServiceVerificationRead, ServiceVerificationRead,
ServiceVerificationWrite, ServiceVerificationWrite,
@@ -159,7 +160,7 @@ func getAccountsStatusCode(cfg *config.Config, sid string, secret string) (int,
if err != nil { if err != nil {
return 0, err return 0, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
return resp.StatusCode, nil return resp.StatusCode, nil
} }
@@ -196,7 +197,7 @@ func getVerifyServicesStatusCode(cfg *config.Config, sid string, secret string)
if err != nil { if err != nil {
return serviceRes, err return serviceRes, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// read response // read response
if err := json.NewDecoder(resp.Body).Decode(&serviceRes); err != nil { if err := json.NewDecoder(resp.Body).Decode(&serviceRes); err != nil {
@@ -224,7 +225,7 @@ func listTwilioAccounts(cfg *config.Config, sid, secret string) ([]service, erro
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
var result struct { var result struct {
Accounts []service `json:"accounts"` Accounts []service `json:"accounts"`
@@ -287,11 +288,12 @@ func printPermissions(statusCode int) {
color.Green("[!] Valid Twilio API Key\n") color.Green("[!] Valid Twilio API Key\n")
color.Green("[i] Expires: Never") color.Green("[i] Expires: Never")
if statusCode == 401 { switch statusCode {
case 401:
color.Yellow("[i] Key type: Standard") color.Yellow("[i] Key type: Standard")
color.Yellow("[i] Permissions: All EXCEPT key management and account/subaccount configuration.") color.Yellow("[i] Permissions: All EXCEPT key management and account/subaccount configuration.")
} else if statusCode == 200 { case 200:
color.Green("[i] Key type: Main (aka Admin)") color.Green("[i] Key type: Main (aka Admin)")
color.Green("[i] Permissions: All") color.Green("[i] Permissions: All")
} }
@@ -111,7 +111,7 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("Failed to open YAML file: %v", err) log.Fatalf("Failed to open YAML file: %v", err)
} }
defer file.Close() defer func() { _ = file.Close() }()
var data PermissionsData var data PermissionsData
decoder := yaml.NewDecoder(file) decoder := yaml.NewDecoder(file)
@@ -135,7 +135,7 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("Failed to create output file: %v", err) log.Fatalf("Failed to create output file: %v", err)
} }
defer outputFile.Close() defer func() { _ = outputFile.Close() }()
err = tmpl.Execute(outputFile, data) err = tmpl.Execute(outputFile, data)
if err != nil { if err != nil {
+2 -2
View File
@@ -47,11 +47,11 @@ func (b *Buffer) Write(data []byte) (int, error) {
} }
size := len(data) size := len(data)
bufferLength := b.Buffer.Len() bufferLength := b.Len()
totalSizeNeeded := bufferLength + size totalSizeNeeded := bufferLength + size
// If the total size is within the threshold, write to the buffer. // If the total size is within the threshold, write to the buffer.
availableSpace := b.Buffer.Cap() - bufferLength availableSpace := b.Cap() - bufferLength
growSize := totalSizeNeeded - bufferLength growSize := totalSizeNeeded - bufferLength
if growSize > availableSpace { if growSize > availableSpace {
// We are manually growing the buffer so we can track the growth via metrics. // We are manually growing the buffer so we can track the growth via metrics.
+1 -1
View File
@@ -73,7 +73,7 @@ func CleanTempArtifacts(ctx logContext.Context) error {
if err != nil { if err != nil {
return fmt.Errorf("error opening temp dir: %w", err) return fmt.Errorf("error opening temp dir: %w", err)
} }
defer dir.Close() defer func() { _ = dir.Close() }()
for { for {
entries, err := dir.ReadDir(1) // read only one entry entries, err := dir.ReadDir(1) // read only one entry
+2 -2
View File
@@ -144,14 +144,14 @@ func TestFilterFromFile(t *testing.T) {
if err := testFilterWriteFile(includeTestFile, []byte(test.includeFileContents)); err != nil { if err := testFilterWriteFile(includeTestFile, []byte(test.includeFileContents)); err != nil {
t.Fatalf("failed to create include rules file: %s", err) t.Fatalf("failed to create include rules file: %s", err)
} }
defer os.Remove(includeTestFile) defer func() { _ = os.Remove(includeTestFile) }()
} }
if test.excludeFile { if test.excludeFile {
excludeTestFile = "/tmp/trufflehog_test_xfilter.txt" excludeTestFile = "/tmp/trufflehog_test_xfilter.txt"
if err := testFilterWriteFile(excludeTestFile, []byte(test.excludeFileContents)); err != nil { if err := testFilterWriteFile(excludeTestFile, []byte(test.excludeFileContents)); err != nil {
t.Fatalf("failed to create include rules file: %s", err) t.Fatalf("failed to create include rules file: %s", err)
} }
defer os.Remove(excludeTestFile) defer func() { _ = os.Remove(excludeTestFile) }()
} }
filter, err := FilterFromFiles(includeTestFile, excludeTestFile) filter, err := FilterFromFiles(includeTestFile, excludeTestFile)
+3 -3
View File
@@ -395,7 +395,7 @@ func TestSaneHttpClientMetrics(t *testing.T) {
resp, err := client.Get(requestURL) resp, err := client.Get(requestURL)
require.NoError(t, err) require.NoError(t, err)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
assert.Equal(t, tc.expectedStatusCode, resp.StatusCode) assert.Equal(t, tc.expectedStatusCode, resp.StatusCode)
// Check that request counter was incremented // Check that request counter was incremented
@@ -462,7 +462,7 @@ func TestRetryableHttpClientMetrics(t *testing.T) {
resp, err := client.Get(requestURL) resp, err := client.Get(requestURL)
require.NoError(t, err) require.NoError(t, err)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
assert.Equal(t, tc.expectedStatusCode, resp.StatusCode) assert.Equal(t, tc.expectedStatusCode, resp.StatusCode)
// Check that request counter was incremented // Check that request counter was incremented
@@ -494,7 +494,7 @@ func TestInstrumentedTransport(t *testing.T) {
// Make a request // Make a request
resp, err := client.Get(server.URL) resp, err := client.Get(server.URL)
require.NoError(t, err) require.NoError(t, err)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Verify the request was successful // Verify the request was successful
assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, http.StatusOK, resp.StatusCode)
+1 -1
View File
@@ -54,7 +54,7 @@ func GetSecret(ctx context.Context, gcpProject, name string) (secret *Secret, er
if err != nil { if err != nil {
return nil, errors.Errorf("failed to create secretmanager client: %v", err) return nil, errors.Errorf("failed to create secretmanager client: %v", err)
} }
defer client.Close() defer func() { _ = client.Close() }()
req := &secretmanagerpb.AccessSecretVersionRequest{ req := &secretmanagerpb.AccessSecretVersionRequest{
Name: parent, Name: parent,
+17 -17
View File
@@ -208,7 +208,7 @@ func TestHTML_FromChunk(t *testing.T) {
{ {
// Block elements (<p>) produce newline boundaries so adjacent // Block elements (<p>) produce newline boundaries so adjacent
// paragraphs don't merge tokens. // paragraphs don't merge tokens.
name: "block elements produce newlines", name: "block elements produce newlines",
chunk: &sources.Chunk{Data: []byte(`<div><p>first</p><p>second</p></div>`)}, chunk: &sources.Chunk{Data: []byte(`<div><p>first</p><p>second</p></div>`)},
want: "first\nsecond", want: "first\nsecond",
}, },
@@ -336,39 +336,39 @@ func TestHTML_FromChunk(t *testing.T) {
{ {
// Zero-width spaces inserted between characters by rich text editors // Zero-width spaces inserted between characters by rich text editors
// are stripped so detector regexes can match the full token. // are stripped so detector regexes can match the full token.
name: "zero-width space stripped from secret", name: "zero-width space stripped from secret",
chunk: &sources.Chunk{Data: []byte("<p>TOKEN_\u200BABCDEF_1234</p>")}, chunk: &sources.Chunk{Data: []byte("<p>TOKEN_\u200BABCDEF_1234</p>")},
want: "TOKEN_ABCDEF_1234", want: "TOKEN_ABCDEF_1234",
}, },
{ {
// Multiple invisible codepoint types mixed into a single token. // Multiple invisible codepoint types mixed into a single token.
name: "multiple invisible character types stripped", name: "multiple invisible character types stripped",
chunk: &sources.Chunk{Data: []byte("<p>SECRET\u200C_VALUE\u00AD_HERE\u2060_END\uFEFF</p>")}, chunk: &sources.Chunk{Data: []byte("<p>SECRET\u200C_VALUE\u00AD_HERE\u2060_END\uFEFF</p>")},
want: "SECRET_VALUE_HERE_END", want: "SECRET_VALUE_HERE_END",
}, },
// --- SVG xlink:href attribute extraction --- // --- SVG xlink:href attribute extraction ---
{ {
// SVG elements use xlink:href for URLs which may contain tokens. // SVG elements use xlink:href for URLs which may contain tokens.
name: "xlink:href extracted from SVG element", name: "xlink:href extracted from SVG element",
chunk: &sources.Chunk{Data: []byte(`<svg><a xlink:href="https://api.example.com?token=secret_value_123">icon</a></svg>`)}, chunk: &sources.Chunk{Data: []byte(`<svg><a xlink:href="https://api.example.com?token=secret_value_123">icon</a></svg>`)},
want: "https://api.example.com?token=secret_value_123\nicon", want: "https://api.example.com?token=secret_value_123\nicon",
}, },
// --- Double-encoded HTML entity decoding --- // --- Double-encoded HTML entity decoding ---
{ {
// Content double-encoded as &amp;amp; becomes &amp; after the parser's // Content double-encoded as &amp;amp; becomes &amp; after the parser's
// first pass; the residual entity replacer decodes it to &. // first pass; the residual entity replacer decodes it to &.
name: "double-encoded ampersand decoded", name: "double-encoded ampersand decoded",
chunk: &sources.Chunk{Data: []byte(`<p>key=abc&amp;amp;secret=val</p>`)}, chunk: &sources.Chunk{Data: []byte(`<p>key=abc&amp;amp;secret=val</p>`)},
want: "key=abc&secret=val", want: "key=abc&secret=val",
}, },
{ {
// Single-encoded entities are handled by the parser; verify the // Single-encoded entities are handled by the parser; verify the
// residual replacer does not corrupt already-decoded content. // residual replacer does not corrupt already-decoded content.
name: "single-encoded entities not double-decoded", name: "single-encoded entities not double-decoded",
chunk: &sources.Chunk{Data: []byte(`<p>5 &gt; 3 &amp; 2 &lt; 4</p>`)}, chunk: &sources.Chunk{Data: []byte(`<p>5 &gt; 3 &amp; 2 &lt; 4</p>`)},
want: "5 > 3 & 2 < 4", want: "5 > 3 & 2 < 4",
}, },
// --- Integration: all extraction types in one chunk --- // --- Integration: all extraction types in one chunk ---
@@ -398,7 +398,7 @@ func TestHTML_FromChunk(t *testing.T) {
if tt.wantNil { if tt.wantNil {
if got != nil { if got != nil {
t.Errorf("FromChunk() = %q, want nil", string(got.Chunk.Data)) t.Errorf("FromChunk() = %q, want nil", string(got.Data))
} }
return return
} }
@@ -409,8 +409,8 @@ func TestHTML_FromChunk(t *testing.T) {
if got.DecoderType != detectorspb.DecoderType_HTML { if got.DecoderType != detectorspb.DecoderType_HTML {
t.Errorf("DecoderType = %v, want %v", got.DecoderType, detectorspb.DecoderType_HTML) t.Errorf("DecoderType = %v, want %v", got.DecoderType, detectorspb.DecoderType_HTML)
} }
if string(got.Chunk.Data) != tt.want { if string(got.Data) != tt.want {
t.Errorf("FromChunk() data =\n%q\nwant:\n%q", string(got.Chunk.Data), tt.want) t.Errorf("FromChunk() data =\n%q\nwant:\n%q", string(got.Data), tt.want)
} }
}) })
} }
@@ -423,7 +423,7 @@ func TestHTML_FeatureFlagDisabled(t *testing.T) {
d := &HTML{} d := &HTML{}
chunk := &sources.Chunk{Data: []byte(`<p>secret: hunter2</p>`)} chunk := &sources.Chunk{Data: []byte(`<p>secret: hunter2</p>`)}
if got := d.FromChunk(chunk); got != nil { if got := d.FromChunk(chunk); got != nil {
t.Errorf("FromChunk() should return nil when disabled, got %q", string(got.Chunk.Data)) t.Errorf("FromChunk() should return nil when disabled, got %q", string(got.Data))
} }
} }
@@ -439,8 +439,8 @@ func TestHTML_FeatureFlagEnabled(t *testing.T) {
if got == nil { if got == nil {
t.Fatal("FromChunk() returned nil, want decoded chunk") t.Fatal("FromChunk() returned nil, want decoded chunk")
} }
if string(got.Chunk.Data) != "secret: hunter2" { if string(got.Data) != "secret: hunter2" {
t.Errorf("FromChunk() data = %q, want %q", string(got.Chunk.Data), "secret: hunter2") t.Errorf("FromChunk() data = %q, want %q", string(got.Data), "secret: hunter2")
} }
} }
+3 -2
View File
@@ -3,10 +3,11 @@ package abstract
import ( import (
"context" "context"
"fmt" "fmt"
regexp "github.com/wasilibs/go-re2"
"net/http" "net/http"
"strings" "strings"
regexp "github.com/wasilibs/go-re2"
"github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
@@ -80,7 +81,7 @@ func verifyAbstract(ctx context.Context, client *http.Client, resMatch string) (
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://docs.abstractapi.com/exchange-rates#response-and-error-codes // https://docs.abstractapi.com/exchange-rates#response-and-error-codes
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -83,7 +83,7 @@ func verifyAbuseIPDB(ctx context.Context, client *http.Client, resMatch string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
switch res.StatusCode { switch res.StatusCode {
case http.StatusOK: case http.StatusOK:
+1 -1
View File
@@ -81,7 +81,7 @@ func verifyAbyssale(ctx context.Context, client *http.Client, resMatch string) (
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
switch res.StatusCode { switch res.StatusCode {
case http.StatusOK: case http.StatusOK:
+1 -1
View File
@@ -93,7 +93,7 @@ func verifyAccuweather(ctx context.Context, client *http.Client, key string) (bo
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://developer.accuweather.com/accuweather-locations-api/apis/get/locations/v1/cities/autocomplete // https://developer.accuweather.com/accuweather-locations-api/apis/get/locations/v1/cities/autocomplete
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -79,7 +79,7 @@ func verifyAdafruitIO(ctx context.Context, client *http.Client, resMatch string)
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://learn.adafruit.com/adafruit-io/http-status-codes // https://learn.adafruit.com/adafruit-io/http-status-codes
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -91,7 +91,7 @@ func verifyAdzuna(ctx context.Context, client *http.Client, resMatch, resIdMatch
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://developer.adzuna.com/overview // https://developer.adzuna.com/overview
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -93,7 +93,7 @@ func verifyAeroworkflow(ctx context.Context, client *http.Client, resMatch, resI
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://api.aeroworkflow.com/swagger/index.html // https://api.aeroworkflow.com/swagger/index.html
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -99,7 +99,7 @@ func verifyAgora(ctx context.Context, client *http.Client, resMatch, resSecret s
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://docs.agora.io/en/voice-calling/reference/agora-console-rest-api#get-all-projects // https://docs.agora.io/en/voice-calling/reference/agora-console-rest-api#get-all-projects
switch res.StatusCode { switch res.StatusCode {
+1 -1
View File
@@ -106,7 +106,7 @@ func verifyAha(ctx context.Context, client *http.Client, resMatch, resURLMatch s
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
// https://www.aha.io/api // https://www.aha.io/api
switch res.StatusCode { switch res.StatusCode {
+4 -4
View File
@@ -75,9 +75,9 @@ func GetSignature(input, key string) string {
} }
func buildStringToSign(method, input string) string { func buildStringToSign(method, input string) string {
filter := strings.Replace(input, "+", "%20", -1) filter := strings.ReplaceAll(input, "+", "%20")
filter = strings.Replace(filter, "%7E", "~", -1) filter = strings.ReplaceAll(filter, "%7E", "~")
filter = strings.Replace(filter, "*", "%2A", -1) filter = strings.ReplaceAll(filter, "*", "%2A")
filter = method + "&%2F&" + url.QueryEscape(filter) filter = method + "&%2F&" + url.QueryEscape(filter)
return filter return filter
} }
@@ -155,7 +155,7 @@ func verifyAlibaba(ctx context.Context, client *http.Client, resIdMatch, resMatc
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
var alibabaResp alibabaResp var alibabaResp alibabaResp
if err = json.NewDecoder(res.Body).Decode(&alibabaResp); err != nil { if err = json.NewDecoder(res.Body).Decode(&alibabaResp); err != nil {
+1 -1
View File
@@ -106,7 +106,7 @@ func verifyAnthropicKey(ctx context.Context, client *http.Client, endpoint, key
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
switch res.StatusCode { switch res.StatusCode {
case http.StatusOK: case http.StatusOK:
+2 -2
View File
@@ -37,7 +37,7 @@ func TestApacta_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"abcd1234-ef56-gh78-ij90-klmn1234opqr"}, want: []string{"abcd1234-ef56-gh78-ij90-klmn1234opqr"},
@@ -73,7 +73,7 @@ func TestApacta_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+3 -2
View File
@@ -4,10 +4,11 @@ import (
"context" "context"
b64 "encoding/base64" b64 "encoding/base64"
"fmt" "fmt"
regexp "github.com/wasilibs/go-re2"
"net/http" "net/http"
"strings" "strings"
regexp "github.com/wasilibs/go-re2"
"github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
@@ -65,7 +66,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} else if res.StatusCode == 401 { } else if res.StatusCode == 401 {
+1 -1
View File
@@ -58,7 +58,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
if err == nil { if err == nil {
bodyString := string(bodyBytes) bodyString := string(bodyBytes)
validResponse := strings.Contains(bodyString, `"status":"success"`) validResponse := strings.Contains(bodyString, `"status":"success"`)
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
if validResponse { if validResponse {
s1.Verified = true s1.Verified = true
+1 -1
View File
@@ -65,7 +65,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} }
+3 -2
View File
@@ -2,10 +2,11 @@ package autopilot
import ( import (
"context" "context"
regexp "github.com/wasilibs/go-re2"
"net/http" "net/http"
"strings" "strings"
regexp "github.com/wasilibs/go-re2"
"github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"
@@ -52,7 +53,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
req.Header.Add("autopilotapikey", resMatch) req.Header.Add("autopilotapikey", resMatch)
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} }
+1 -1
View File
@@ -336,7 +336,7 @@ func (s scanner) CleanResults(results []detectors.Result) []detectors.Result {
// Reference: https://nitter.poast.org/TalBeerySec/status/1816449053841838223#m // Reference: https://nitter.poast.org/TalBeerySec/status/1816449053841838223#m
func checkSessionToken(sessionToken string, secret string) bool { func checkSessionToken(sessionToken string, secret string) bool {
if !(strings.Contains(sessionToken, "YXdz") || strings.Contains(sessionToken, "Jb3JpZ2luX2Vj")) || if (!strings.Contains(sessionToken, "YXdz") && !strings.Contains(sessionToken, "Jb3JpZ2luX2Vj")) ||
strings.Contains(sessionToken, secret) { strings.Contains(sessionToken, secret) {
// Handle error if the sessionToken is not a valid base64 string // Handle error if the sessionToken is not a valid base64 string
return false return false
+1 -1
View File
@@ -116,7 +116,7 @@ func verifyMatch(ctx context.Context, client *http.Client, endpoint, accountName
} }
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -30,7 +30,7 @@ var (
passwordPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", "password"}) + `\b(git&[0-9]{12}&[a-zA-Z0-9\/+]{85}[a-zA-Z0-9]==)`) passwordPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", "password"}) + `\b(git&[0-9]{12}&[a-zA-Z0-9\/+]{85}[a-zA-Z0-9]==)`)
invalidHosts = simple.NewCache[struct{}]() invalidHosts = simple.NewCache[struct{}]()
noSuchHostErr = errors.New("Could not resolve host") errNoSuchHost = errors.New("could not resolve host")
) )
const ( const (
@@ -82,7 +82,7 @@ EndpointLoop:
isVerified, err := verifyUrlPassword(ctx, urlMatch, azureGitUsername, passwordMatch) isVerified, err := verifyUrlPassword(ctx, urlMatch, azureGitUsername, passwordMatch)
s1.Verified = isVerified s1.Verified = isVerified
if err != nil { if err != nil {
if errors.Is(err, noSuchHostErr) { if errors.Is(err, errNoSuchHost) {
invalidHosts.Set(urlMatch, struct{}{}) invalidHosts.Set(urlMatch, struct{}{})
continue EndpointLoop continue EndpointLoop
} }
@@ -156,7 +156,7 @@ func verifyUrlPassword(_ context.Context, repoUrl, user, password string) (bool,
if strings.Contains(outputString, "Authentication failed") { if strings.Contains(outputString, "Authentication failed") {
return false, nil return false, nil
} else if strings.Contains(outputString, "Could not resolve host") { } else if strings.Contains(outputString, "Could not resolve host") {
return false, noSuchHostErr return false, errNoSuchHost
} }
return false, err return false, err
} }
@@ -31,7 +31,7 @@ var (
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", ".azure-api.net", "subscription", "key"}) + `([a-zA-Z-0-9]{32})`) // pattern for both Primary and secondary key keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", ".azure-api.net", "subscription", "key"}) + `([a-zA-Z-0-9]{32})`) // pattern for both Primary and secondary key
invalidHosts = simple.NewCache[struct{}]() invalidHosts = simple.NewCache[struct{}]()
noSuchHostErr = errors.New("no such host") errNoSuchHost = errors.New("no such host")
) )
// Keywords are used for efficiently pre-filtering chunks. // Keywords are used for efficiently pre-filtering chunks.
@@ -81,7 +81,7 @@ EndpointLoop:
isVerified, verificationErr := s.verifyMatch(ctx, client, baseUrl, key) isVerified, verificationErr := s.verifyMatch(ctx, client, baseUrl, key)
s1.Verified = isVerified s1.Verified = isVerified
if verificationErr != nil { if verificationErr != nil {
if errors.Is(verificationErr, noSuchHostErr) { if errors.Is(verificationErr, errNoSuchHost) {
invalidHosts.Set(baseUrl, struct{}{}) invalidHosts.Set(baseUrl, struct{}{})
continue EndpointLoop continue EndpointLoop
} }
@@ -120,7 +120,7 @@ func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, baseUrl,
if err != nil { if err != nil {
return false, nil return false, nil
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -153,7 +153,7 @@ func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, endpoint,
if err != nil { if err != nil {
return false, fmt.Errorf("request failed: %w", err) return false, fmt.Errorf("request failed: %w", err)
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check the response status // Check the response status
switch resp.StatusCode { switch resp.StatusCode {
@@ -104,7 +104,7 @@ EndpointLoop:
r.Verified = true r.Verified = true
} }
if verificationErr != nil { if verificationErr != nil {
if errors.Is(verificationErr, noSuchHostErr) { if errors.Is(verificationErr, errNoSuchHost) {
invalidHosts.Set(username, struct{}{}) invalidHosts.Set(username, struct{}{})
continue EndpointLoop continue EndpointLoop
} }
@@ -126,7 +126,7 @@ func (s Scanner) IsFalsePositive(_ detectors.Result) (bool, string) {
return false, "" return false, ""
} }
var noSuchHostErr = errors.New("no such host") var errNoSuchHost = errors.New("no such host")
func verifyMatch(ctx context.Context, client *http.Client, username string, password string) (bool, error) { func verifyMatch(ctx context.Context, client *http.Client, username string, password string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s.azurecr.io/v2/", username), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s.azurecr.io/v2/", username), nil)
@@ -139,7 +139,7 @@ func verifyMatch(ctx context.Context, client *http.Client, username string, pass
if err != nil { if err != nil {
// lookup foo.azurecr.io: no such host // lookup foo.azurecr.io: no such host
if strings.Contains(err.Error(), "no such host") { if strings.Contains(err.Error(), "no such host") {
return false, noSuchHostErr return false, errNoSuchHost
} }
return false, err return false, err
} }
@@ -68,7 +68,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
req.SetBasicAuth("", resMatch) req.SetBasicAuth("", resMatch)
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
hasVerifiedRes, _ := common.ResponseContainsSubstring(res.Body, "lastUpdateTime") hasVerifiedRes, _ := common.ResponseContainsSubstring(res.Body, "lastUpdateTime")
if res.StatusCode >= 200 && res.StatusCode < 300 && hasVerifiedRes { if res.StatusCode >= 200 && res.StatusCode < 300 && hasVerifiedRes {
s1.Verified = true s1.Verified = true
@@ -37,7 +37,7 @@ var (
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", ".management.azure-api.net"}) + `([a-zA-Z0-9+\/]{83,85}[a-zA-Z0-9]==)`) // pattern for both Primary and secondary key keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", ".management.azure-api.net"}) + `([a-zA-Z0-9+\/]{83,85}[a-zA-Z0-9]==)`) // pattern for both Primary and secondary key
invalidHosts = simple.NewCache[struct{}]() invalidHosts = simple.NewCache[struct{}]()
noSuchHostErr = errors.New("no such host") errNoSuchHost = errors.New("no such host")
) )
// Keywords are used for efficiently pre-filtering chunks. // Keywords are used for efficiently pre-filtering chunks.
@@ -87,7 +87,7 @@ EndpointLoop:
isVerified, verificationErr := s.verifyMatch(ctx, client, baseUrl, serviceName, key) isVerified, verificationErr := s.verifyMatch(ctx, client, baseUrl, serviceName, key)
s1.Verified = isVerified s1.Verified = isVerified
if verificationErr != nil { if verificationErr != nil {
if errors.Is(verificationErr, noSuchHostErr) { if errors.Is(verificationErr, errNoSuchHost) {
invalidHosts.Set(baseUrl, struct{}{}) invalidHosts.Set(baseUrl, struct{}{})
continue EndpointLoop continue EndpointLoop
} }
@@ -133,7 +133,7 @@ func (s Scanner) verifyMatch(ctx context.Context, client *http.Client, baseUrl,
if err != nil { if err != nil {
return false, nil return false, nil
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -64,7 +64,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
} }
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} else if res.StatusCode == 401 { } else if res.StatusCode == 401 {
+4 -4
View File
@@ -37,7 +37,7 @@ var (
invalidStorageAccounts = simple.NewCache[struct{}]() invalidStorageAccounts = simple.NewCache[struct{}]()
noSuchHostErr = errors.New("no such host") errNoSuchHost = errors.New("no such host")
) )
func (s Scanner) Keywords() []string { func (s Scanner) Keywords() []string {
@@ -101,7 +101,7 @@ UrlLoop:
s1.Verified = isVerified s1.Verified = isVerified
if verificationErr != nil { if verificationErr != nil {
if errors.Is(verificationErr, noSuchHostErr) { if errors.Is(verificationErr, errNoSuchHost) {
invalidStorageAccounts.Set(storageAccount, struct{}{}) invalidStorageAccounts.Set(storageAccount, struct{}{})
continue UrlLoop continue UrlLoop
} }
@@ -131,11 +131,11 @@ func verifyMatch(ctx context.Context, client *http.Client, url, key string, retr
res, err := client.Do(req) res, err := client.Do(req)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "no such host") { if strings.Contains(err.Error(), "no such host") {
return false, noSuchHostErr return false, errNoSuchHost
} }
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
bodyBytes, err := io.ReadAll(res.Body) bodyBytes, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
@@ -69,7 +69,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} else if res.StatusCode == 401 || res.StatusCode == 403 { } else if res.StatusCode == 401 || res.StatusCode == 403 {
@@ -69,7 +69,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
res, err := client.Do(req) res, err := client.Do(req)
if err == nil { if err == nil {
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 { if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true s1.Verified = true
} else if res.StatusCode == 401 || res.StatusCode == 403 { } else if res.StatusCode == 401 || res.StatusCode == 403 {
@@ -39,7 +39,7 @@ func TestBannerBear_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"yvxpthLIcYpZweFpPOVeCOtt"}, want: []string{"yvxpthLIcYpZweFpPOVeCOtt"},
@@ -77,7 +77,7 @@ func TestBannerBear_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -39,7 +39,7 @@ func TestBannerBear_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"bb_pr_abcdc2b40ef44abcd8cbf3739aabcd"}, want: []string{"bb_pr_abcdc2b40ef44abcd8cbf3739aabcd"},
@@ -77,7 +77,7 @@ func TestBannerBear_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -39,7 +39,7 @@ func TestBareMetrics_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"sk_nGDJWCkPiFAKE5XFTzUUA"}, want: []string{"sk_nGDJWCkPiFAKE5XFTzUUA"},
@@ -77,7 +77,7 @@ func TestBareMetrics_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -38,7 +38,7 @@ func TestBeamer_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"DyVdf7+cAXw4MH9gT1CPotU31RMl__aLKbrABRWvT7TyO="}, want: []string{"DyVdf7+cAXw4MH9gT1CPotU31RMl__aLKbrABRWvT7TyO="},
@@ -75,7 +75,7 @@ func TestBeamer_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -39,7 +39,7 @@ func TestBeeBole_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"bn6htprmfpukfalts4muwalxh9j15ucvnrfdme8t"}, want: []string{"bn6htprmfpukfalts4muwalxh9j15ucvnrfdme8t"},
@@ -77,7 +77,7 @@ func TestBeeBole_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -39,7 +39,7 @@ func TestBeSnappy_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"f58c5d37d7876d32cfdd823f8fe4ded364a8d483b5dbfadcc55ad801b3be8523"}, want: []string{"f58c5d37d7876d32cfdd823f8fe4ded364a8d483b5dbfadcc55ad801b3be8523"},
@@ -77,7 +77,7 @@ func TestBeSnappy_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -36,7 +36,7 @@ func TestBestTime_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"pri_099889f14d114dfaae476569b395eade"}, want: []string{"pri_099889f14d114dfaae476569b395eade"},
@@ -71,7 +71,7 @@ func TestBestTime_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -38,7 +38,7 @@ func TestBetterStack_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
func getBetterStackToken() string{ return "ntJD0ER8QpuT0O1WqsclApO2" } func getBetterStackToken() string{ return "ntJD0ER8QpuT0O1WqsclApO2" }
`, `,
@@ -76,7 +76,7 @@ func TestBetterStack_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
func getBetterStackToken() string{ return "DyntJD0ER8QpuT0O1WqsclApO2" } func getBetterStackToken() string{ return "DyntJD0ER8QpuT0O1WqsclApO2" }
`, `,
+1 -1
View File
@@ -38,7 +38,7 @@ func TestBilloMat_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status // Check response status
if resp.StatusCode == http.StatusOK { if resp.StatusCode == http.StatusOK {
@@ -39,7 +39,7 @@ func TestBingsubscriptionkey_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
}`, }`,
want: []string{"89017d414ed64edb9c776d4a52102b9a"}, want: []string{"89017d414ed64edb9c776d4a52102b9a"},
}, },
@@ -77,7 +77,7 @@ func TestBingsubscriptionkey_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
}`, }`,
want: []string{}, want: []string{},
}, },
+2 -2
View File
@@ -42,7 +42,7 @@ func TestBitBar_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"64pq66z15thg8fh3acd00l35lpyg7c82"}, want: []string{"64pq66z15thg8fh3acd00l35lpyg7c82"},
@@ -83,7 +83,7 @@ func TestBitBar_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -43,7 +43,7 @@ func TestBitCoinAverage_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"WZizqeWvRnhZmFlpc5pMc92NP1Du19wxxpd5zjsYY8F"}, want: []string{"WZizqeWvRnhZmFlpc5pMc92NP1Du19wxxpd5zjsYY8F"},
@@ -85,7 +85,7 @@ func TestBitCoinAverage_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -39,7 +39,7 @@ func TestBitlyAccessToken_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"2xN7puShxzNf5fZleQthTg305lKr7KrbW95D3gSD"}, want: []string{"2xN7puShxzNf5fZleQthTg305lKr7KrbW95D3gSD"},
@@ -77,7 +77,7 @@ func TestBitlyAccessToken_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -46,7 +46,7 @@ func TestBitmex_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"EPwUIxOIveS463D_2O9LFgkzW_HlMtrmELzXm4bSlWv49JLcgvg5hvu467WbbnpmoEA-RjrY"}, want: []string{"EPwUIxOIveS463D_2O9LFgkzW_HlMtrmELzXm4bSlWv49JLcgvg5hvu467WbbnpmoEA-RjrY"},
@@ -91,7 +91,7 @@ func TestBitmex_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -39,7 +39,7 @@ func TestBlazeMeter_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"sjbuxa3m-vs4n-ykl8-8jpv-i09hdidciolp"}, want: []string{"sjbuxa3m-vs4n-ykl8-8jpv-i09hdidciolp"},
@@ -77,7 +77,7 @@ func TestBlazeMeter_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -39,7 +39,7 @@ func TestBlitApp_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"I_MncTA8nlFcqlBCakI5vwkwFD4_zRUYZKt8hyd"}, want: []string{"I_MncTA8nlFcqlBCakI5vwkwFD4_zRUYZKt8hyd"},
@@ -77,7 +77,7 @@ func TestBlitApp_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -39,7 +39,7 @@ func TestBlockNative_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"76e50995-059f-3d1a-af8e-cc85fc05eb03"}, want: []string{"76e50995-059f-3d1a-af8e-cc85fc05eb03"},
@@ -77,7 +77,7 @@ func TestBlockNative_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -34,7 +34,7 @@ func TestBlogger_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status // Check response status
if resp.StatusCode == http.StatusOK { if resp.StatusCode == http.StatusOK {
@@ -74,7 +74,7 @@ func TestBlogger_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status // Check response status
if resp.StatusCode == http.StatusOK { if resp.StatusCode == http.StatusOK {
+2 -2
View File
@@ -39,7 +39,7 @@ func TestBoostNote_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"fb1026ac5994e3ad01799fe040289317ba2594a20e9e45307a143be82b49d213"}, want: []string{"fb1026ac5994e3ad01799fe040289317ba2594a20e9e45307a143be82b49d213"},
@@ -77,7 +77,7 @@ func TestBoostNote_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+2 -2
View File
@@ -40,7 +40,7 @@ func TestBorgBase_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"FoHclCFSi_aV09jowJQ4RUF_MiqW6ioqq6_OcyB0PFlV-mQ1yoFjk5JLlxbzRUzKTA6vsfR8wq6TNc83rtNKlkD092Sj1c9CbPVBXlHksy.sT2I/so6bMGdPcqxzbjrxYgAUiORgqJDeTet4gKOQlZpt"}, want: []string{"FoHclCFSi_aV09jowJQ4RUF_MiqW6ioqq6_OcyB0PFlV-mQ1yoFjk5JLlxbzRUzKTA6vsfR8wq6TNc83rtNKlkD092Sj1c9CbPVBXlHksy.sT2I/so6bMGdPcqxzbjrxYgAUiORgqJDeTet4gKOQlZpt"},
@@ -79,7 +79,7 @@ func TestBorgBase_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -113,7 +113,7 @@ func verifyBraintree(ctx context.Context, client *http.Client, url, pubKey, priv
}() }()
bodyString := string(bodyBytes) bodyString := string(bodyBytes)
if !(res.StatusCode == http.StatusOK) { if res.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode) return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
} }
@@ -40,7 +40,7 @@ func TestBrainTreePayments_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"f7b3cb83a7fdb915a71ce17ab8a903cc"}, want: []string{"f7b3cb83a7fdb915a71ce17ab8a903cc"},
@@ -79,7 +79,7 @@ func TestBrainTreePayments_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
@@ -39,7 +39,7 @@ func TestBrandFetch_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{"uHOAdwfQ7sD2yOpur72UqyUeIqnFwILOIlEPyBtJ"}, want: []string{"uHOAdwfQ7sD2yOpur72UqyUeIqnFwILOIlEPyBtJ"},
@@ -77,7 +77,7 @@ func TestBrandFetch_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+1 -1
View File
@@ -95,7 +95,7 @@ func VerifyMatch(ctx context.Context, client *http.Client, token string) (bool,
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusOK: case http.StatusOK:
@@ -49,7 +49,7 @@ func TestBrandFetch_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
// Check response status // Check response status
if resp.StatusCode == http.StatusOK { if resp.StatusCode == http.StatusOK {
@@ -104,7 +104,7 @@ func TestBrandFetch_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,
+1 -1
View File
@@ -106,7 +106,7 @@ func verifyBrowserStackCredentials(ctx context.Context, client *http.Client, use
if err != nil { if err != nil {
return false, err return false, err
} }
defer res.Body.Close() defer func() { _ = res.Body.Close() }()
if res.StatusCode == http.StatusOK { if res.StatusCode == http.StatusOK {
return true, nil return true, nil
@@ -44,7 +44,7 @@ func TestBrowserStack_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: []string{ want: []string{
@@ -92,7 +92,7 @@ func TestBrowserStack_Pattern(t *testing.T) {
// Perform the request // Perform the request
client := &http.Client{} client := &http.Client{}
resp, _ := client.Do(req) resp, _ := client.Do(req)
defer resp.Body.Close() defer func() { _ = resp.Body.Close() }()
} }
`, `,
want: nil, want: nil,

Some files were not shown because too many files have changed in this diff Show More