Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 33 additions & 11 deletions pkg/detectors/youtubeapikey/youtubeapikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package youtubeapikey

import (
"context"
"fmt"
"net/http"
"strings"

Expand All @@ -14,6 +15,7 @@ import (

type Scanner struct {
detectors.DefaultMultiPartCredentialProvider
client *http.Client
}

// Ensure the Scanner satisfies the interface at compile time.
Expand All @@ -33,6 +35,13 @@ func (s Scanner) Keywords() []string {
return []string{"youtube"}
}

func (s Scanner) getClient() *http.Client {
if s.client != nil {
return s.client
}
return client
}

// FromData will find and optionally verify YoutubeApiKey secrets in a given set of bytes.
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)
Expand All @@ -53,17 +62,9 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}

if verify {
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.googleapis.com/youtube/v3/channelSections?key="+resMatch+"&channelId="+resIdmatch, nil)
if err != nil {
continue
}
res, err := client.Do(req)
if err == nil {
defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
}
}
isVerified, verificationErr := verifyYoutubeAPIKey(ctx, s.getClient(), resMatch, resIdmatch)
s1.Verified = isVerified
s1.SetVerificationError(verificationErr, resMatch)
}

results = append(results, s1)
Expand All @@ -74,6 +75,27 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
return results, nil
}

func verifyYoutubeAPIKey(ctx context.Context, client *http.Client, key, channelID string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.googleapis.com/youtube/v3/channelSections?key="+key+"&channelId="+channelID, nil)
if err != nil {
return false, err
}
res, err := client.Do(req)
if err != nil {
return false, err
}
defer func() { _ = res.Body.Close() }()

switch res.StatusCode {
case http.StatusOK:
return true, nil
case http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden:
return false, nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK, Google does return 403 for valid credentials that lack proper authorization. Could you double check this?

Error type	Error detail	Description
forbidden (403)	forbidden	Access forbidden. The request may not be properly authorized.

default:
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}

func (s Scanner) Type() detector_typepb.DetectorType {
return detector_typepb.DetectorType_YoutubeApiKey
}
Expand Down
55 changes: 50 additions & 5 deletions pkg/detectors/youtubeapikey/youtubeapikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@ package youtubeapikey
import (
"context"
"fmt"
"net/http"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick"
)

var (
validKey = "8SN8OtkzJ6z2tcFtv93Gl63o97LGGBvYAyJviDg"
invalidKey = "8SN8OtkzJ6z2tcFtv93?l63o97LGGBvYAyJviDg"
validId = "0ifNmkGT6biPToj9TDGYqyFP"
invalidId = "0ifNmkG?6biPToj9TDGYqyFP"
keyword = "youtubeapikey"
validKey = "8SN8OtkzJ6z2tcFtv93Gl63o97LGGBvYAyJviDg"
invalidKey = "8SN8OtkzJ6z2tcFtv93?l63o97LGGBvYAyJviDg"
validId = "0ifNmkGT6biPToj9TDGYqyFP"
invalidId = "0ifNmkG?6biPToj9TDGYqyFP"
keyword = "youtubeapikey"
)

func TestYoutubeApiKey_Pattern(t *testing.T) {
Expand Down Expand Up @@ -81,3 +84,45 @@ func TestYoutubeApiKey_Pattern(t *testing.T) {
})
}
}

func TestYoutubeApiKey_Verification(t *testing.T) {
tests := []struct {
name string
statusCode int
wantVerified bool
wantVerificationErr string
}{
{
name: "verified",
statusCode: http.StatusOK,
wantVerified: true,
},
{
name: "unverified",
statusCode: http.StatusBadRequest,
},
{
name: "verification error",
statusCode: http.StatusInternalServerError,
wantVerificationErr: "unexpected HTTP response status 500",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
d := Scanner{client: common.ConstantResponseHttpClient(test.statusCode, "{}")}
input := fmt.Sprintf("%s token - '%s'\n%s token - '%s'\n", keyword, validKey, keyword, validId)

results, err := d.FromData(context.Background(), true, []byte(input))
require.NoError(t, err)
require.Len(t, results, 1)
require.Equal(t, test.wantVerified, results[0].Verified)

if test.wantVerificationErr == "" {
require.NoError(t, results[0].VerificationError())
} else {
require.EqualError(t, results[0].VerificationError(), test.wantVerificationErr)
}
})
}
}