package redhatpyxis import ( "context" "fmt" "io" "net/http" regexp "github.com/wasilibs/go-re2" "github.com/trufflesecurity/trufflehog/v3/pkg/common" "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" ) type Scanner struct { client *http.Client } // Compile-time interface check var _ detectors.Detector = (*Scanner)(nil) var ( defaultClient = detectors.NewClientWithDedup(common.SaneHttpClient()) pyxisAPIKeyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"redhat", "pyxis"}) + `\b([a-z0-9]{32})\b`) ) // Keywords used for fast pre-filtering func (s Scanner) Keywords() []string { return []string{ "redhat", "pyxis", } } func (s Scanner) getClient() *http.Client { if s.client != nil { return s.client } return defaultClient } // FromData scans for Red Hat Pyxis API keys and optionally verifies them. func (s Scanner) FromData( ctx context.Context, verify bool, data []byte, ) (results []detectors.Result, err error) { dataStr := string(data) uniqueTokens := make(map[string]struct{}) for _, match := range pyxisAPIKeyPat.FindAllStringSubmatch(dataStr, -1) { uniqueTokens[match[1]] = struct{}{} } for token := range uniqueTokens { result := detectors.Result{ DetectorType: detector_typepb.DetectorType_RedHatPyxis, Raw: []byte(token), SecretParts: map[string]string{ "key": token, }, } if verify { verified, verificationErr := verifyPyxisAPIKey( ctx, s.getClient(), token, ) result.SetVerificationError(verificationErr, token) result.Verified = verified } results = append(results, result) } return } func verifyPyxisAPIKey( ctx context.Context, client *http.Client, token string, ) (bool, error) { req, err := http.NewRequestWithContext( ctx, http.MethodGet, "https://catalog.redhat.com/api/containers/v1/projects/certification/requests/images?page_size=1&page=0", http.NoBody, ) if err != nil { return false, err } req.Header.Set("X-API-KEY", token) res, err := detectors.DoWithDedup(client, detector_typepb.DetectorType_RedHatPyxis, token, req) if err != nil { return false, err } defer func() { _, _ = io.Copy(io.Discard, res.Body) _ = res.Body.Close() }() switch res.StatusCode { case http.StatusOK: return true, nil case http.StatusUnauthorized: // Invalid API key return false, nil default: return false, fmt.Errorf( "unexpected HTTP response status %d", res.StatusCode, ) } } func (s Scanner) Type() detector_typepb.DetectorType { return detector_typepb.DetectorType_RedHatPyxis } func (s Scanner) Description() string { return "Red Hat Pyxis is a container certification and metadata management platform. Red Hat Pyxis API keys can be used to authenticate against the Red Hat Ecosystem Catalog APIs and access container certification resources and metadata." }