Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Add OAuth2 (ROPC) auth for verification requests (#5392)
Dave Hubbardb2b0a92070f2
diff --git a/pkg/custom_detectors/CUSTOM_DETECTORS.md b/pkg/custom_detectors/CUSTOM_DETECTORS.mdindex f149f81f0..95fb2165d 100644--- a/pkg/custom_detectors/CUSTOM_DETECTORS.md+++ b/pkg/custom_detectors/CUSTOM_DETECTORS.md@@ -39,7 +39,7 @@ This guide will walk you through setting up a custom detector in TruffleHog to i- **`successRanges`**: A list of HTTP status codes (or ranges) that indicate the secret is **live** (active). When the verification server responds with a matching status code, the secret is marked as verified. Each entry can be a single code (`"200"`) or an inclusive range (`"200-202"`). If omitted (along with `rotatedRanges`), only `200` is treated as verified (backward compatible).- **`rotatedRanges`**: A list of HTTP status codes (or ranges) that indicate the secret has been **rotated** (no longer active). When the verification server responds with a matching status code, the secret is definitively marked as unverified.- When only one of the two fields is configured, non-matching responses are treated as the opposite state (e.g., if only `successRanges` is set, any response that doesn't match is treated as rotated; if only `rotatedRanges` is set, any non-matching response is treated as live). When both fields are configured and the response matches neither, the result is treated as unknown/inconclusive.+ When only one of the two fields is configured, non-matching responses are treated as the opposite state (e.g., if only `successRanges` is set, any response that doesn't match is treated as rotated; if only `rotatedRanges` is set, any non-matching response is treated as live). When both fields are configured and the response matches neither, the result is treated as unknown/inconclusive. If no endpoint returns a response at all (for example a network error or an [auth](#authenticating-verification-requests) failure), the result carries a verification error rather than being reported as simply unverified.Since `verify` is optional, Custom Detectors can also be used without a webhook to flag generic hardcoded secrets (e.g. `*.password=`, `*.secret=`) in config files such as `.properties`, `.env`, or `.yaml`. [Here](/examples/generic_config_secrets.yml) is an example config tuned for that use case.@@ -67,6 +67,33 @@ This guide will walk you through setting up a custom detector in TruffleHog to iIn this example, a `200` response from the verification server means the secret is live and needs rotation. A `401` or `403` means the secret has been rotated and is no longer active. Any other response is treated as inconclusive.+ #### Authenticating verification requests++ If the verification endpoint sits behind an OAuth2-protected proxy, add an `auth` block. TruffleHog obtains an access token from the identity provider and sends it as `Bearer <token>` on every request to that endpoint's host.++ The only supported grant type is the Resource Owner Password Credentials (ROPC) grant ([RFC 6749 section 4.3](https://datatracker.ietf.org/doc/html/rfc6749#section-4.3)), configured under `ropc`. TruffleHog logs in with a service account's username and password plus the OAuth2 client's credentials, and repeats that login whenever the token expires. Other grants, such as client credentials or refresh tokens, are not supported.++ ```yaml+ verify:+ - endpoint: https://verifier.example.com/+ # Must be true if endpoint or tokenEndpoint uses HTTP+ unsafe: false+ auth:+ oauth2:+ tokenEndpoint: https://idp.example.com/oauth2/token+ tokenHeader: X-Proxy-Authorization # optional, defaults to Authorization+ ropc:+ username: scanner+ password: scanner-password+ clientId: trufflehog+ clientSecret: client-secret # optional+ scope: verify # optional, space-separated+ ```++ - The token is fetched on first use, reused until shortly before it expires, and never sent to any other host. If the identity provider doesn't say when the token expires, it is treated as valid for 5 minutes.+ - `headers` may not set the `tokenHeader`; the config is rejected at startup if it does.+ - If a token can't be obtained, affected results carry a verification error and the scan continues. Failed logins are retried with backoff (5 seconds, doubling up to 5 minutes) to avoid account lockouts.+**Other allowed parameters:**- **`primary_regex_name`**: This parameter allows you designate the primary regex pattern when multiple regex patterns are defined in the regex section. If a match is found, the match for the designated primary regex will be used to determine the line number. The value must be one of the names specified in the regex section. If not provided, the first regex name in sorted order will be used as the primary regex by default.- **`exclude_regexes_capture`**: This parameter allows you to define regex patterns to exclude specific parts of a detected secret. If a match is found within the detected secret, the portion matching this regex is excluded from the result.diff --git a/pkg/custom_detectors/custom_detectors.go b/pkg/custom_detectors/custom_detectors.goindex c2683269d..934c3f368 100644--- a/pkg/custom_detectors/custom_detectors.go+++ b/pkg/custom_detectors/custom_detectors.go@@ -5,6 +5,7 @@ import ("context""encoding/json""errors"+ "fmt""io""maps""net/http"@@ -16,6 +17,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth""github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb")@@ -30,6 +32,13 @@ const maxTotalMatches = 100// initialization).type CustomRegexWebhook struct {*custom_detectorspb.CustomRegex++ // verifyClients holds the HTTP client for each entry of Verify, by index.+ // Verifiers without auth share httpClient; a verifier with auth gets a+ // copy whose transport attaches an access token to requests for its+ // endpoint. They are built once here so every verification for an auth+ // config shares one cached token.+ verifyClients []*http.Client}// Ensure the Scanner satisfies the interface at compile time.@@ -58,6 +67,7 @@ func NewWebhookCustomRegex(pb *custom_detectorspb.CustomRegex) (*CustomRegexWebhreturn nil, err}+ verifyClients := make([]*http.Client, 0, len(pb.Verify))for _, verify := range pb.Verify {if err := ValidateVerifyEndpoint(verify.Endpoint, verify.Unsafe); err != nil {return nil, err@@ -71,13 +81,53 @@ func NewWebhookCustomRegex(pb *custom_detectorspb.CustomRegex) (*CustomRegexWebhif err := ValidateVerifyRanges(verify.RotatedRanges); err != nil {return nil, err}++ // Auth is validated and built here so a bad config fails at load+ // time. No token is fetched until the first verification.+ authCfg, err := verifierauth.FromProto(verify.GetAuth(), verify.Unsafe)+ if err != nil {+ return nil, fmt.Errorf("verifier auth for %q: %w", verify.Endpoint, err)+ }+ if authCfg == nil {+ verifyClients = append(verifyClients, httpClient)+ continue+ }+ if err := validateHeadersAvoidTokenHeader(verify.Headers, authCfg.TokenHeader()); err != nil {+ return nil, err+ }+ verifyClients = append(verifyClients, authCfg.WrapClient(httpClient, []string{verify.Endpoint}))}// Ensure primary regex name is set.ensurePrimaryRegexNameSet(pb)// TODO: Copy only necessary data out of pb.- return &CustomRegexWebhook{pb}, nil+ return &CustomRegexWebhook{CustomRegex: pb, verifyClients: verifyClients}, nil+}++// validateHeadersAvoidTokenHeader rejects a verify headers entry for the+// header the access token is written to. The auth transport refuses to+// overwrite a header the request already carries, so such a verifier could+// never send a request; failing at load time says so up front.+func validateHeadersAvoidTokenHeader(headers []string, tokenHeader string) error {+ for _, header := range headers {+ key, _, _ := strings.Cut(header, ":")+ if http.CanonicalHeaderKey(strings.TrimSpace(key)) == tokenHeader {+ return fmt.Errorf("header %q is the oauth2 tokenHeader; set tokenHeader to a different header or remove this header", header)+ }+ }+ return nil+}++// verifyClient returns the HTTP client for the Verify entry at index i.+// A CustomRegexWebhook built without NewWebhookCustomRegex has no+// per-verifier clients; it falls back to the shared client and never+// attaches auth.+func (c *CustomRegexWebhook) verifyClient(i int) *http.Client {+ if i < len(c.verifyClients) {+ return c.verifyClients[i]+ }+ return httpClient}var httpClient = common.SaneHttpClient()@@ -235,6 +285,7 @@ func (c *CustomRegexWebhook) createResults(ctx context.Context, match map[string}var raw string+ secrets := make([]string, 0, len(match))for _, key := range slices.Sorted(maps.Keys(match)) {values := match[key]// values[0] contains the entire regex match.@@ -244,6 +295,7 @@ func (c *CustomRegexWebhook) createResults(ctx context.Context, match map[stringsecret = values[1]}raw += secret+ secrets = append(secrets, secret)// We set the full regex match as the primary secret value.// Reasoning:@@ -286,10 +338,14 @@ func (c *CustomRegexWebhook) createResults(ctx context.Context, match map[stringvar (definitive boolrangesInEffect bool+ // requestErr is the most recent verifier request that got no+ // response at all: a network, TLS, or timeout error, or a verifier+ // auth failure (no access token, or a header collision).+ requestErr error)// Try each config until we get a definitive answer.- for _, verifyConfig := range c.GetVerify() {+ for i, verifyConfig := range c.GetVerify() {if common.IsDone(ctx) {return ctx.Err()}@@ -307,8 +363,9 @@ func (c *CustomRegexWebhook) createResults(ctx context.Context, match map[stringif req.Header.Get("Content-Type") == "" {req.Header.Set("Content-Type", "application/json")}- resp, err := httpClient.Do(req)+ resp, err := c.verifyClient(i).Do(req)if err != nil {+ requestErr = errcontinue}defer func() {@@ -366,8 +423,18 @@ func (c *CustomRegexWebhook) createResults(ctx context.Context, match map[string// Both configured but neither matched -- try the next verifier.}- if rangesInEffect && !definitive {- result.SetVerificationError(errors.New("verification response status code did not match any configured successRanges or rotatedRanges"))+ // Without a definitive answer the result is "unable to verify", never a+ // silent "not verified". A request that got no response says more about+ // why than a status code that matched no range, so it is reported first.+ // A legacy verifier's non-200 counts as an answer, so a later request+ // error after it does not turn the result into an error.+ if !definitive {+ switch {+ case requestErr != nil:+ result.SetVerificationError(requestErr, secrets...)+ case rangesInEffect:+ result.SetVerificationError(errors.New("verification response status code did not match any configured successRanges or rotatedRanges"))+ }}select {diff --git a/pkg/custom_detectors/custom_detectors_test.go b/pkg/custom_detectors/custom_detectors_test.goindex 760971b68..8f56045fd 100644--- a/pkg/custom_detectors/custom_detectors_test.go+++ b/pkg/custom_detectors/custom_detectors_test.go@@ -2,16 +2,20 @@ package custom_detectorsimport ("context"+ "io""net/http""net/http/httptest""strings"+ "sync/atomic""testing""github.com/google/go-cmp/cmp""github.com/google/go-cmp/cmp/cmpopts""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth/verifierauthtest""github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb""github.com/trufflesecurity/trufflehog/v3/pkg/protoyaml"@@ -137,7 +141,7 @@ func TestCustomDetectorsParsing(t *testing.T) {func TestFromData_InvalidRegEx(t *testing.T) {c := &CustomRegexWebhook{- &custom_detectorspb.CustomRegex{+ CustomRegex: &custom_detectorspb.CustomRegex{Name: "Internal bi tool",Keywords: []string{"secret_v1_", "pat_v2_"},Regex: map[string]string{@@ -787,6 +791,46 @@ func TestNewWebhookCustomRegex_Validation(t *testing.T) {wantErr: true,wantErrSubstr: "invalid http status code",},+ {+ name: "VerifierAuth: valid with a tokenHeader the headers do not use",+ mutate: func(pb *custom_detectorspb.CustomRegex) {+ pb.Verify[0].Auth = ropcAuth("https://idp.example.com/token", "X-Auth-Proxy-Token")+ },+ },+ {+ name: "VerifierAuth: http token endpoint without unsafe=true",+ mutate: func(pb *custom_detectorspb.CustomRegex) {+ pb.Verify[0].Auth = ropcAuth("http://idp.example.com/token", "X-Auth-Proxy-Token")+ },+ wantErr: true,+ wantErrSubstr: "oauth2 tokenEndpoint: http endpoint must have unsafe=true",+ },+ {+ name: "VerifierAuth: incomplete ropc credentials",+ mutate: func(pb *custom_detectorspb.CustomRegex) {+ pb.Verify[0].Auth = ropcAuth("https://idp.example.com/token", "X-Auth-Proxy-Token")+ pb.Verify[0].Auth.GetOauth2().GetRopc().Username = ""+ },+ wantErr: true,+ wantErrSubstr: "oauth2 ropc username is required",+ },+ {+ name: "VerifierAuth: headers entry for the default token header",+ mutate: func(pb *custom_detectorspb.CustomRegex) {+ pb.Verify[0].Auth = ropcAuth("https://idp.example.com/token", "")+ },+ wantErr: true,+ wantErrSubstr: `header "Authorization: Bearer x" is the oauth2 tokenHeader`,+ },+ {+ name: "VerifierAuth: headers entry for a custom token header in another case",+ mutate: func(pb *custom_detectorspb.CustomRegex) {+ pb.Verify[0].Headers = []string{"x-auth-proxy-token: static"}+ pb.Verify[0].Auth = ropcAuth("https://idp.example.com/token", "X-Auth-Proxy-Token")+ },+ wantErr: true,+ wantErrSubstr: "is the oauth2 tokenHeader",+ },}for _, tt := range tests {@@ -989,6 +1033,203 @@ func TestVerificationMixedRangedAndLegacyVerifiers(t *testing.T) {assert.Nil(t, results[0].VerificationError(), "legacy success must not produce a spurious verification error")}+// ropcAuth builds a verify auth config for the ROPC grant against+// tokenEndpoint. An empty tokenHeader means the default, Authorization.+func ropcAuth(tokenEndpoint, tokenHeader string) *custom_detectorspb.VerifierAuth {+ return &custom_detectorspb.VerifierAuth{+ AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{+ Oauth2: &custom_detectorspb.OAuth2Config{+ TokenEndpoint: tokenEndpoint,+ TokenHeader: tokenHeader,+ GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{+ Ropc: &custom_detectorspb.ROPCConfig{+ Username: "svc-scanner",+ Password: "svc-password",+ ClientId: "scanner-client",+ },+ },+ },+ },+ }+}++func TestCustomRegexParsingWithVerifierAuth(t *testing.T) {+ testYaml := `name: test+keywords:+- secret+regex:+ token: ([a-zA-Z0-9]{32})+verify:+- endpoint: https://verify.example.com/+ auth:+ oauth2:+ tokenEndpoint: https://idp.example.com/oauth2/token+ tokenHeader: X-Auth-Proxy-Token+ ropc:+ username: svc-scanner+ password: svc-password+ clientId: scanner-client+ clientSecret: client-secret+ scope: verify openid`++ var got custom_detectorspb.CustomRegex+ require.NoError(t, protoyaml.UnmarshalStrict([]byte(testYaml), &got))+ require.Len(t, got.Verify, 1)+ oauth2 := got.Verify[0].GetAuth().GetOauth2()+ require.NotNil(t, oauth2)+ assert.Equal(t, "https://idp.example.com/oauth2/token", oauth2.GetTokenEndpoint())+ assert.Equal(t, "X-Auth-Proxy-Token", oauth2.GetTokenHeader())+ assert.Equal(t, "svc-scanner", oauth2.GetRopc().GetUsername())+ assert.Equal(t, "svc-password", oauth2.GetRopc().GetPassword())+ assert.Equal(t, "scanner-client", oauth2.GetRopc().GetClientId())+ assert.Equal(t, "client-secret", oauth2.GetRopc().GetClientSecret())+ assert.Equal(t, "verify openid", oauth2.GetRopc().GetScope())+}++// newVerifyDetector builds a single-regex custom detector with the given+// verify configs; the data "secret_ABCDEFGHIJ" produces one match.+func newVerifyDetector(t *testing.T, verify ...*custom_detectorspb.VerifierConfig) *CustomRegexWebhook {+ t.Helper()+ detector, err := NewWebhookCustomRegex(&custom_detectorspb.CustomRegex{+ Name: "test",+ Keywords: []string{"secret"},+ Regex: map[string]string{"token": `(secret_[a-zA-Z0-9]{10})`},+ Verify: verify,+ })+ require.NoError(t, err)+ return detector+}++func verifyOne(t *testing.T, detector *CustomRegexWebhook) detectors.Result {+ t.Helper()+ results, err := detector.FromData(context.Background(), true, []byte("secret_ABCDEFGHIJ"))+ require.NoError(t, err)+ require.Len(t, results, 1)+ return results[0]+}++// closedServerURL returns the URL of a server that is no longer listening,+// so requests to it fail with a connection error.+func closedServerURL(t *testing.T) string {+ t.Helper()+ ts := httptest.NewServer(http.NotFoundHandler())+ ts.Close()+ return ts.URL+}++func TestVerification_VerifierAuthSendsTokenAlongsideConfiguredHeaders(t *testing.T) {+ t.Parallel()+ idp := verifierauthtest.NewIdP(t)++ var gotAuthorization, gotToken, gotBody string+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotAuthorization = r.Header.Get("Authorization")+ gotToken = r.Header.Get("X-Auth-Proxy-Token")+ body, _ := io.ReadAll(r.Body)+ gotBody = string(body)+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ auth := ropcAuth(idp.URL, "X-Auth-Proxy-Token")+ result := verifyOne(t, newVerifyDetector(t, &custom_detectorspb.VerifierConfig{+ Endpoint: ts.URL,+ Unsafe: true,+ Headers: []string{"Authorization: Bearer static"},+ Auth: auth,+ }))++ assert.True(t, result.Verified)+ assert.NoError(t, result.VerificationError())+ assert.Equal(t, "Bearer "+verifierauthtest.AccessToken, gotToken)+ assert.Equal(t, "Bearer static", gotAuthorization, "configured headers are sent unchanged")+ assert.JSONEq(t, `{"test": {"token": ["secret_ABCDEFGHIJ", "secret_ABCDEFGHIJ"]}}`, gotBody, "the standard body is unchanged")+}++func TestVerification_VerifierAuthTokenFailureIsAVerificationError(t *testing.T) {+ t.Parallel()+ idp := verifierauthtest.NewIdP(t)+ idp.RejectCredentials()++ var hits atomic.Int32+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ result := verifyOne(t, newVerifyDetector(t, &custom_detectorspb.VerifierConfig{+ Endpoint: ts.URL,+ Unsafe: true,+ Auth: ropcAuth(idp.URL, ""),+ }))++ assert.False(t, result.Verified)+ assert.ErrorContains(t, result.VerificationError(), "verifier auth: could not obtain access token")+ assert.Zero(t, hits.Load(), "nothing is sent without a token")+}++func TestVerification_RequestErrorRule(t *testing.T) {+ t.Parallel()++ status := func(code int) string {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(code)+ }))+ t.Cleanup(ts.Close)+ return ts.URL+ }++ tests := []struct {+ name string+ verify []*custom_detectorspb.VerifierConfig+ wantVerified bool+ wantVerifyErr bool+ }{+ {+ name: "only verifier unreachable -> verification error",+ verify: []*custom_detectorspb.VerifierConfig{{Endpoint: closedServerURL(t), Unsafe: true}},+ wantVerifyErr: true,+ },+ {+ name: "unreachable, then legacy 200 -> verified, no error",+ verify: []*custom_detectorspb.VerifierConfig{+ {Endpoint: closedServerURL(t), Unsafe: true},+ {Endpoint: status(http.StatusOK), Unsafe: true},+ },+ wantVerified: true,+ },+ {+ name: "legacy 401, then unreachable -> the 401 is the answer, no error",+ verify: []*custom_detectorspb.VerifierConfig{+ {Endpoint: status(http.StatusUnauthorized), Unsafe: true},+ {Endpoint: closedServerURL(t), Unsafe: true},+ },+ },+ {+ name: "ranged non-match, then unreachable -> verification error",+ verify: []*custom_detectorspb.VerifierConfig{+ {Endpoint: status(http.StatusInternalServerError), Unsafe: true, SuccessRanges: []string{"200"}, RotatedRanges: []string{"401"}},+ {Endpoint: closedServerURL(t), Unsafe: true},+ },+ wantVerifyErr: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ result := verifyOne(t, newVerifyDetector(t, tt.verify...))+ assert.Equal(t, tt.wantVerified, result.Verified)+ if tt.wantVerifyErr {+ assert.Error(t, result.VerificationError())+ } else {+ assert.NoError(t, result.VerificationError())+ }+ })+ }+}+func BenchmarkProductIndices(b *testing.B) {for i := 0; i < b.N; i++ {_ = productIndices(3, 2, 6)diff --git a/pkg/custom_detectors/validation.go b/pkg/custom_detectors/validation.goindex cb81ae5c4..ceb846ec6 100644--- a/pkg/custom_detectors/validation.go+++ b/pkg/custom_detectors/validation.go@@ -5,6 +5,8 @@ import ("regexp" //nolint:depguard // used instead of github.com/wasilibs/go-re2 due to differences in utf-8 handling"strconv""strings"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth")func ValidateKeywords(keywords []string) error {@@ -52,15 +54,10 @@ func ValidatePrimaryRegexName(primaryRegexName string, regexes map[string]stringreturn nil}+// ValidateVerifyEndpoint checks a verify endpoint with the same rule that+// verifier auth applies to token endpoints, so the two cannot drift.func ValidateVerifyEndpoint(endpoint string, unsafe bool) error {- if len(endpoint) == 0 {- return fmt.Errorf("no endpoint")- }-- if strings.HasPrefix(endpoint, "http://") && !unsafe {- return fmt.Errorf("http endpoint must have unsafe=true")- }- return nil+ return verifierauth.ValidateEndpoint(endpoint, unsafe)}func ValidateVerifyHeaders(headers []string) error {diff --git a/pkg/detectors/artifactory/artifactory.go b/pkg/detectors/artifactory/artifactory.goindex 9881c3464..76b9d905c 100644--- a/pkg/detectors/artifactory/artifactory.go+++ b/pkg/detectors/artifactory/artifactory.go@@ -1,6 +1,7 @@package artifactoryimport (+ "cmp""context""errors""fmt"@@ -47,10 +48,7 @@ func (s Scanner) Keywords() []string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// FromData will find and optionally verify Artifactory secrets in a given set of bytes.diff --git a/pkg/detectors/artifactoryreferencetoken/artifactoryreferencetoken.go b/pkg/detectors/artifactoryreferencetoken/artifactoryreferencetoken.goindex 09e8599f7..464acb3bb 100644--- a/pkg/detectors/artifactoryreferencetoken/artifactoryreferencetoken.go+++ b/pkg/detectors/artifactoryreferencetoken/artifactoryreferencetoken.go@@ -1,6 +1,7 @@package artifactoryreferencetokenimport (+ "cmp""context""errors""fmt"@@ -45,11 +46,7 @@ func (s Scanner) Keywords() []string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }-- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// FromData will find and optionally verify Artifactory Reference tokens in a given set of bytes.diff --git a/pkg/detectors/atlassiandatacenter/bitbucketdatacenter/bitbucketdatacenter.go b/pkg/detectors/atlassiandatacenter/bitbucketdatacenter/bitbucketdatacenter.goindex 1a9dba072..c53d5ca40 100644--- a/pkg/detectors/atlassiandatacenter/bitbucketdatacenter/bitbucketdatacenter.go+++ b/pkg/detectors/atlassiandatacenter/bitbucketdatacenter/bitbucketdatacenter.go@@ -1,6 +1,7 @@package bitbucketdatacenterimport (+ "cmp""context""fmt""net/http"@@ -70,10 +71,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result}if verify {- client := s.client- if client == nil {- client = defaultClient- }+ client := s.VerificationClient(cmp.Or(s.client, defaultClient))isVerified, verificationErr := verifyMatch(ctx, client, secret, bitBucketURL)s1.Verified = isVerifieddiff --git a/pkg/detectors/atlassiandatacenter/confluencedatacenter/confluencedatacenter.go b/pkg/detectors/atlassiandatacenter/confluencedatacenter/confluencedatacenter.goindex 492ffffb9..94295d422 100644--- a/pkg/detectors/atlassiandatacenter/confluencedatacenter/confluencedatacenter.go+++ b/pkg/detectors/atlassiandatacenter/confluencedatacenter/confluencedatacenter.go@@ -1,6 +1,7 @@package confluencedatacenterimport (+ "cmp""context""errors""fmt"@@ -52,10 +53,7 @@ func (s Scanner) Description() string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {diff --git a/pkg/detectors/atlassiandatacenter/jiradatacenterpat/jiradatacenterpat.go b/pkg/detectors/atlassiandatacenter/jiradatacenterpat/jiradatacenterpat.goindex 9a7af9e97..ca5004d82 100644--- a/pkg/detectors/atlassiandatacenter/jiradatacenterpat/jiradatacenterpat.go+++ b/pkg/detectors/atlassiandatacenter/jiradatacenterpat/jiradatacenterpat.go@@ -1,6 +1,7 @@package jiradatacenterpatimport (+ "cmp""context""net/http"@@ -31,15 +32,12 @@ var (// Since the first byte is always an ASCII digit (0x30–0x39), the first base64 character is always M, N, or O.// This is also verified by generating 25+ tokens.// The trailing boundary (?:[^A-Za-z0-9+/=]|\z) is used instead of \b to correctly handle tokens ending in + or /.- patPat = atlassiandatacenter.GetDCTokenPat(keywords)- urlPat = atlassiandatacenter.GetURLPat(keywords)+ patPat = atlassiandatacenter.GetDCTokenPat(keywords)+ urlPat = atlassiandatacenter.GetURLPat(keywords))func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/datadogapikey/datadogapikey.go b/pkg/detectors/datadogapikey/datadogapikey.goindex b9eb3c404..042a0c8e7 100644--- a/pkg/detectors/datadogapikey/datadogapikey.go+++ b/pkg/detectors/datadogapikey/datadogapikey.go@@ -1,6 +1,7 @@package datadogapikeyimport (+ "cmp""context""fmt""io"@@ -41,10 +42,7 @@ func (s Scanner) Keywords() []string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return client+ return s.VerificationClient(cmp.Or(s.client, client))}// FromData will find and optionally verify DatadogToken secrets in a given set of bytes.diff --git a/pkg/detectors/datadogtoken/datadogtoken.go b/pkg/detectors/datadogtoken/datadogtoken.goindex a3b07d726..f4a12c986 100644--- a/pkg/detectors/datadogtoken/datadogtoken.go+++ b/pkg/detectors/datadogtoken/datadogtoken.go@@ -1,6 +1,7 @@package datadogtokenimport (+ "cmp""context""encoding/json""fmt"@@ -97,10 +98,7 @@ func setOrganizationInfo(opt []*options, s1 *detectors.Result) {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/detectors.go b/pkg/detectors/detectors.goindex dbcec64f2..8d5d97790 100644--- a/pkg/detectors/detectors.go+++ b/pkg/detectors/detectors.go@@ -11,6 +11,7 @@ import ("strings""unicode"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb"@@ -92,6 +93,15 @@ type EndpointCustomizer interface {UseFoundEndpoints(bool)}+// VerifierAuthCustomizer is an optional interface for detectors whose+// configured verification endpoints sit behind an auth proxy. It is separate+// from EndpointCustomizer so existing implementers are unaffected; detectors+// that embed EndpointSetter get it for free, and route their verification+// requests through EndpointSetter.VerificationClient to apply it.+type VerifierAuthCustomizer interface {+ SetVerifierAuth(*verifierauth.Config)+}+type CloudProvider interface {CloudEndpoint() string}diff --git a/pkg/detectors/endpoint_customizer.go b/pkg/detectors/endpoint_customizer.goindex 7cc917d85..d24bda955 100644--- a/pkg/detectors/endpoint_customizer.go+++ b/pkg/detectors/endpoint_customizer.go@@ -2,18 +2,25 @@ package detectorsimport ("fmt"+ "net/http""github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth")// EndpointSetter implements a sensible default for the SetEndpoints function// of the EndpointCustomizer interface. A detector can embed this struct to// gain the functionality.+//+// It also implements VerifierAuthCustomizer. Detectors that embed it opt in+// to verifier auth by building their verification client with+// VerificationClient.type EndpointSetter struct {configuredEndpoints []stringcloudEndpoint stringuseCloudEndpoint booluseFoundEndpoints bool+ verifierAuth *verifierauth.Config}func (e *EndpointSetter) SetConfiguredEndpoints(userConfiguredEndpoints ...string) error {@@ -40,8 +47,26 @@ func (e *EndpointSetter) UseFoundEndpoints(enabled bool) {e.useFoundEndpoints = enabled}+// SetVerifierAuth configures authentication for requests to the configured+// endpoints. A nil config means no auth.+func (e *EndpointSetter) SetVerifierAuth(cfg *verifierauth.Config) {+ e.verifierAuth = cfg+}++// Endpoints returns the endpoints a detector should verify against.+//+// While verifier auth is set, only configured endpoints are returned and the+// cloud and found endpoint flags are ignored. Auth means verification is+// deliberately routed through a private auth proxy, so a secret must never+// be sent to the public API or to an endpoint found in scanned data. The rule is+// applied here, when endpoints are read, rather than by clearing the flags+// in SetVerifierAuth, so a later UseCloudEndpoint(true) from any caller+// cannot re-enable public endpoints.func (e *EndpointSetter) Endpoints(foundEndpoints ...string) []string {endpoints := e.configuredEndpoints+ if e.verifierAuth != nil {+ return endpoints+ }if e.useCloudEndpoint && e.cloudEndpoint != "" {endpoints = append(endpoints, e.cloudEndpoint)}@@ -50,3 +75,15 @@ func (e *EndpointSetter) Endpoints(foundEndpoints ...string) []string {}return endpoints}++// VerificationClient returns the client a detector should use for+// verification requests: base itself when no verifier auth is configured,+// otherwise a copy of base that attaches the access token to requests for+// the configured endpoints. Detectors call it wherever they would otherwise+// use their verification client directly.+func (e *EndpointSetter) VerificationClient(base *http.Client) *http.Client {+ if e.verifierAuth == nil {+ return base+ }+ return e.verifierAuth.WrapClient(base, e.configuredEndpoints)+}diff --git a/pkg/detectors/endpoint_customizer_test.go b/pkg/detectors/endpoint_customizer_test.goindex 0f54118b5..250e6f69b 100644--- a/pkg/detectors/endpoint_customizer_test.go+++ b/pkg/detectors/endpoint_customizer_test.go@@ -1,9 +1,17 @@package detectorsimport (+ "net/http"+ "net/http/httptest"+ "sync/atomic""testing""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth/verifierauthtest"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb")func TestEmbeddedEndpointSetter(t *testing.T) {@@ -58,3 +66,139 @@ func TestEmbeddedEndpointSetter(t *testing.T) {})}++// newTestVerifierAuth builds a verifier auth config backed by a fake IdP that+// always issues "idp-token".+func newTestVerifierAuth(t *testing.T, tokenHeader string) *verifierauth.Config {+ t.Helper()+ idp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"access_token":"idp-token","token_type":"Bearer","expires_in":3600}`))+ }))+ t.Cleanup(idp.Close)++ cfg, err := verifierauth.FromProto(&custom_detectorspb.VerifierAuth{+ AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{Oauth2: &custom_detectorspb.OAuth2Config{+ TokenEndpoint: idp.URL,+ TokenHeader: tokenHeader,+ GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{Ropc: &custom_detectorspb.ROPCConfig{+ Username: "svc", Password: "pw", ClientId: "client",+ }},+ }},+ }, true)+ require.NoError(t, err)+ return cfg+}++func TestEndpointSetter_VerifierAuthRestrictsEndpointsToConfigured(t *testing.T) {+ var s EndpointSetter+ require.NoError(t, s.SetConfiguredEndpoints("https://authproxy.example.com"))+ s.SetCloudEndpoint("https://api.example.com")+ s.UseCloudEndpoint(true)+ s.UseFoundEndpoints(true)+ require.Equal(t,+ []string{"https://authproxy.example.com", "https://api.example.com", "https://found.example.com"},+ s.Endpoints("https://found.example.com"))++ s.SetVerifierAuth(newTestVerifierAuth(t, ""))+ assert.Equal(t, []string{"https://authproxy.example.com"}, s.Endpoints("https://found.example.com"))++ // Re-enabling public endpoints after auth is set must not bring them back.+ s.UseCloudEndpoint(true)+ s.UseFoundEndpoints(true)+ assert.Equal(t, []string{"https://authproxy.example.com"}, s.Endpoints("https://found.example.com"))++ // Clearing auth restores the normal endpoint rules.+ s.SetVerifierAuth(nil)+ assert.Equal(t,+ []string{"https://authproxy.example.com", "https://api.example.com", "https://found.example.com"},+ s.Endpoints("https://found.example.com"))+}++func TestEndpointSetter_VerificationClientWithoutAuthReturnsBase(t *testing.T) {+ var s EndpointSetter+ base := &http.Client{}+ assert.Same(t, base, s.VerificationClient(base))+}++func TestEndpointSetter_VerificationClientAttachesTokenForConfiguredEndpoints(t *testing.T) {+ var gotToken, gotSecret string+ authProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotToken = r.Header.Get("X-Auth-Proxy-Token")+ gotSecret = r.Header.Get("Authorization")+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(authProxy.Close)++ var s EndpointSetter+ require.NoError(t, s.SetConfiguredEndpoints(authProxy.URL))+ s.SetVerifierAuth(newTestVerifierAuth(t, "X-Auth-Proxy-Token"))++ req, err := http.NewRequest(http.MethodGet, authProxy.URL+"/api/v4/user", nil)+ require.NoError(t, err)+ req.Header.Set("Authorization", "Bearer secret-under-test")+ resp, err := s.VerificationClient(authProxy.Client()).Do(req)+ require.NoError(t, err)+ _ = resp.Body.Close()++ assert.Equal(t, "Bearer idp-token", gotToken)+ assert.Equal(t, "Bearer secret-under-test", gotSecret)+}++// Detectors report a failed request through Result.SetVerificationError,+// which keeps only the innermost error's message. Verifier auth failures must+// survive that as a message that names verifier auth and carries the+// oauth2_trace, rather than as whatever the IdP or network returned.+func TestEndpointSetter_VerifierAuthFailuresSurviveSetVerificationError(t *testing.T) {+ var hits atomic.Int32+ authProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(authProxy.Close)++ // verificationError sends a detector-style request through the wrapped+ // client and records the outcome the way a detector would.+ verificationError := func(t *testing.T, s *EndpointSetter, header http.Header) error {+ t.Helper()+ req, err := http.NewRequest(http.MethodGet, authProxy.URL+"/api/v4/user", nil)+ require.NoError(t, err)+ req.Header = header+ resp, err := s.VerificationClient(authProxy.Client()).Do(req)+ if resp != nil {+ _ = resp.Body.Close()+ }+ require.Error(t, err)++ var result Result+ result.SetVerificationError(err, "secret-under-test")+ return result.VerificationError()+ }++ t.Run("header collision", func(t *testing.T) {+ var s EndpointSetter+ require.NoError(t, s.SetConfiguredEndpoints(authProxy.URL))+ s.SetVerifierAuth(verifierauthtest.Config(t, verifierauthtest.NewIdP(t), ""))++ err := verificationError(t, &s, http.Header{"Authorization": {"Bearer secret-under-test"}})+ assert.ErrorContains(t, err, verifierauth.ErrHeaderCollision.Error())+ assert.ErrorContains(t, err, `header "Authorization"`)+ assert.ErrorContains(t, err, "oauth2_trace=")+ assert.NotContains(t, err.Error(), "secret-under-test")+ })++ t.Run("token unavailable", func(t *testing.T) {+ idp := verifierauthtest.NewIdP(t)+ idp.RejectCredentials()+ var s EndpointSetter+ require.NoError(t, s.SetConfiguredEndpoints(authProxy.URL))+ s.SetVerifierAuth(verifierauthtest.Config(t, idp, ""))++ err := verificationError(t, &s, http.Header{})+ assert.ErrorContains(t, err, "verifier auth: could not obtain access token")+ assert.ErrorContains(t, err, "oauth2_trace=")+ assert.NotContains(t, err.Error(), "invalid_grant", "the IdP's error stays in the logs")+ })++ assert.Zero(t, hits.Load(), "neither failure sends the request")+}diff --git a/pkg/detectors/github/v1/github_old.go b/pkg/detectors/github/v1/github_old.goindex 393c16553..a516eb9b3 100644--- a/pkg/detectors/github/v1/github_old.go+++ b/pkg/detectors/github/v1/github_old.go@@ -127,7 +127,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result}if verify {- client := common.SaneHttpClient()+ client := s.VerificationClient(common.SaneHttpClient())isVerified, userResponse, headers, err := s.VerifyGithub(ctx, client, token)diff --git a/pkg/detectors/github/v2/github.go b/pkg/detectors/github/v2/github.goindex e20ef6c28..7db02bf6b 100644--- a/pkg/detectors/github/v2/github.go+++ b/pkg/detectors/github/v2/github.go@@ -95,7 +95,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result}if verify {- client := common.SaneHttpClient()+ client := s.VerificationClient(common.SaneHttpClient())isVerified, userResponse, headers, err := s.VerifyGithub(ctx, client, token)s1.Verified = isVerifieddiff --git a/pkg/detectors/gitlab/v1/gitlab.go b/pkg/detectors/gitlab/v1/gitlab.goindex e77633eb0..eb84baf91 100644--- a/pkg/detectors/gitlab/v1/gitlab.go+++ b/pkg/detectors/gitlab/v1/gitlab.go@@ -1,6 +1,7 @@package gitlabimport (+ "cmp""context""encoding/json""fmt"@@ -48,11 +49,7 @@ type gitlabErrorResponse struct {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }-- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/gitlab/v2/gitlab_v2.go b/pkg/detectors/gitlab/v2/gitlab_v2.goindex cef9fd22f..13e83abb0 100644--- a/pkg/detectors/gitlab/v2/gitlab_v2.go+++ b/pkg/detectors/gitlab/v2/gitlab_v2.go@@ -1,6 +1,7 @@package gitlabimport (+ "cmp""context""fmt""maps"@@ -34,11 +35,7 @@ var ()func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }-- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/gitlab/v3/gitlab_v3.go b/pkg/detectors/gitlab/v3/gitlab_v3.goindex f37098dde..053e4fc7a 100644--- a/pkg/detectors/gitlab/v3/gitlab_v3.go+++ b/pkg/detectors/gitlab/v3/gitlab_v3.go@@ -1,6 +1,7 @@package gitlabimport (+ "cmp""context""fmt""maps"@@ -35,11 +36,7 @@ var ()func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }-- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/gitlaboauth2/gitlaboauth2.go b/pkg/detectors/gitlaboauth2/gitlaboauth2.goindex 814defed7..a7d2be7f3 100644--- a/pkg/detectors/gitlaboauth2/gitlaboauth2.go+++ b/pkg/detectors/gitlaboauth2/gitlaboauth2.go@@ -1,6 +1,7 @@package gitlaboauth2import (+ "cmp""context""encoding/json""fmt"@@ -36,10 +37,7 @@ var ()func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/hashicorpvault/hashicorpvaultbatchtoken/hashicorpvaultbatchtoken.go b/pkg/detectors/hashicorpvault/hashicorpvaultbatchtoken/hashicorpvaultbatchtoken.goindex 6e4abac86..643f93428 100644--- a/pkg/detectors/hashicorpvault/hashicorpvaultbatchtoken/hashicorpvaultbatchtoken.go+++ b/pkg/detectors/hashicorpvault/hashicorpvaultbatchtoken/hashicorpvaultbatchtoken.go@@ -1,6 +1,7 @@package hashicorpbatchtokenimport (+ "cmp""context""fmt""net/http"@@ -44,10 +45,7 @@ func (s Scanner) Description() string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}func (s Scanner) FromData(diff --git a/pkg/detectors/hashicorpvault/hashicorpvaulttoken/hashicorpvaulttoken.go b/pkg/detectors/hashicorpvault/hashicorpvaulttoken/hashicorpvaulttoken.goindex 1b462125c..69def29d5 100644--- a/pkg/detectors/hashicorpvault/hashicorpvaulttoken/hashicorpvaulttoken.go+++ b/pkg/detectors/hashicorpvault/hashicorpvaulttoken/hashicorpvaulttoken.go@@ -1,6 +1,7 @@package hashicorpvaulttokenimport (+ "cmp""context""fmt""net/http"@@ -47,10 +48,7 @@ func (s Scanner) Description() string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}func (s Scanner) FromData(diff --git a/pkg/detectors/hashicorpvaultauth/hashicorpvaultauth.go b/pkg/detectors/hashicorpvaultauth/hashicorpvaultauth.goindex 26057a7bb..347b3f82e 100644--- a/pkg/detectors/hashicorpvaultauth/hashicorpvaultauth.go+++ b/pkg/detectors/hashicorpvaultauth/hashicorpvaultauth.go@@ -2,6 +2,7 @@ package hashicorpvaultauthimport ("bytes"+ "cmp""context""encoding/json""fmt"@@ -95,10 +96,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result}if verify {- client := s.client- if client == nil {- client = defaultClient- }+ client := s.VerificationClient(cmp.Or(s.client, defaultClient))isVerified, verificationErr := verifyMatch(ctx, client, roleId, secretId, vaultUrl)s1.Verified = isVerifieddiff --git a/pkg/detectors/humioapitoken/humioapitoken.go b/pkg/detectors/humioapitoken/humioapitoken.goindex 9364b40e2..b389fde6c 100644--- a/pkg/detectors/humioapitoken/humioapitoken.go+++ b/pkg/detectors/humioapitoken/humioapitoken.go@@ -1,6 +1,7 @@package humioapitokenimport (+ "cmp""context""fmt""io"@@ -79,10 +80,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result}if verify {- client := s.client- if client == nil {- client = defaultClient- }+ client := s.VerificationClient(cmp.Or(s.client, defaultClient))// Verification only targets known SaaS regions (US via// CloudEndpoint, EU via additionalCloudEndpoints) plus anydiff --git a/pkg/detectors/jiratoken/v1/jiratoken.go b/pkg/detectors/jiratoken/v1/jiratoken.goindex 65027e261..b50c9efb3 100644--- a/pkg/detectors/jiratoken/v1/jiratoken.go+++ b/pkg/detectors/jiratoken/v1/jiratoken.go@@ -2,6 +2,7 @@ package jiratokenimport ("bytes"+ "cmp""context""encoding/json""errors"@@ -137,10 +138,7 @@ type JIRAGraphQLResponse struct {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/jiratoken/v2/jiratoken_v2.go b/pkg/detectors/jiratoken/v2/jiratoken_v2.goindex 90e275d7e..bb070ccd1 100644--- a/pkg/detectors/jiratoken/v2/jiratoken_v2.go+++ b/pkg/detectors/jiratoken/v2/jiratoken_v2.go@@ -1,6 +1,7 @@package jiratokenimport (+ "cmp""context""fmt""net/http"@@ -41,10 +42,7 @@ var ()func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// Keywords are used for efficiently pre-filtering chunks.diff --git a/pkg/detectors/sumologickey/sumologickey.go b/pkg/detectors/sumologickey/sumologickey.goindex 2cf01fab5..80289134b 100644--- a/pkg/detectors/sumologickey/sumologickey.go+++ b/pkg/detectors/sumologickey/sumologickey.go@@ -1,6 +1,7 @@package sumologickeyimport (+ "cmp""context""fmt""io"@@ -90,10 +91,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result)if verify {- client := s.client- if client == nil {- client = defaultClient- }+ client := s.VerificationClient(cmp.Or(s.client, defaultClient))// Endpoints applies the engine's endpoint configuration:// configured verifier endpoints, the US cloud endpoint, anddiff --git a/pkg/detectors/tableau/tableau.go b/pkg/detectors/tableau/tableau.goindex a6c163e71..42b0deb48 100644--- a/pkg/detectors/tableau/tableau.go+++ b/pkg/detectors/tableau/tableau.go@@ -2,6 +2,7 @@ package tableauimport ("bytes"+ "cmp""context""encoding/json""fmt"@@ -51,10 +52,7 @@ func (s Scanner) Keywords() []string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {diff --git a/pkg/detectors/user/user.go b/pkg/detectors/user/user.goindex d0ec714ec..350921f85 100644--- a/pkg/detectors/user/user.go+++ b/pkg/detectors/user/user.go@@ -1,6 +1,7 @@package userimport (+ "cmp""context""errors""fmt"@@ -44,10 +45,7 @@ func (s Scanner) Keywords() []string {}func (s Scanner) getClient() *http.Client {- if s.client != nil {- return s.client- }- return defaultClient+ return s.VerificationClient(cmp.Or(s.client, defaultClient))}// FromData will find and optionally verify User secrets in a given set of bytes.diff --git a/pkg/detectors/verification_client_wiring_test.go b/pkg/detectors/verification_client_wiring_test.gonew file mode 100644index 000000000..1ef623093--- /dev/null+++ b/pkg/detectors/verification_client_wiring_test.go@@ -0,0 +1,103 @@+package detectors_test++import (+ "bytes"+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/defaults"+)++// modulePrefix is stripped from a detector's package path to find its source+// directory relative to the repository root.+const modulePrefix = "github.com/trufflesecurity/trufflehog/v3/"++// The engine can give verifier auth to any default detector that satisfies+// VerifierAuthCustomizer, whether it embeds EndpointSetter directly or+// inherits it by embedding another detector's Scanner (as GitHub v2 embeds+// v1). The token is only attached if the detector builds its verification+// client with VerificationClient. A detector that skips the wrap still accepts+// auth and sends unauthenticated requests, which an auth proxy answers as if+// every secret were invalid. No runtime check can see which client a detector+// uses, so this test reads the source of the package that defines each+// detector's concrete type, which is where its FromData lives.+func TestVerifierAuthDetectorsUseVerificationClient(t *testing.T) {+ scanned := make(map[string]bool)+ for _, d := range defaults.DefaultDetectors() {+ if _, ok := d.(detectors.VerifierAuthCustomizer); !ok {+ continue+ }++ typ := reflect.TypeOf(d)+ if typ.Kind() == reflect.Pointer {+ typ = typ.Elem()+ }+ pkgPath := typ.PkgPath()+ if _, done := scanned[pkgPath]; done {+ continue+ }++ rel, ok := strings.CutPrefix(pkgPath, modulePrefix)+ require.True(t, ok, "detector %s is defined outside this module", pkgPath)+ // The test runs in pkg/detectors, two levels below the repository root.+ calls, err := callsVerificationClient(filepath.Join("..", "..", rel))+ require.NoError(t, err)+ scanned[pkgPath] = calls++ assert.True(t, calls,+ "%s accepts verifier auth but never calls VerificationClient; build the verification client with s.VerificationClient(...)", pkgPath)+ }+ assert.NotEmpty(t, scanned, "found no default detectors that accept verifier auth; the check is broken")+}++// callsVerificationClient reports whether any non-test Go file in dir calls a+// method named VerificationClient.+func callsVerificationClient(dir string) (bool, error) {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return false, err+ }++ fset := token.NewFileSet()+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ src, err := os.ReadFile(filepath.Join(dir, name))+ if err != nil {+ return false, err+ }+ if !bytes.Contains(src, []byte("VerificationClient")) {+ continue+ }+ file, err := parser.ParseFile(fset, name, src, 0)+ if err != nil {+ return false, err+ }++ var calls bool+ ast.Inspect(file, func(n ast.Node) bool {+ if call, ok := n.(*ast.CallExpr); ok {+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "VerificationClient" {+ calls = true+ }+ }+ return !calls+ })+ if calls {+ return true, nil+ }+ }+ return false, nil+}diff --git a/pkg/detectors/verifierauth/token_source.go b/pkg/detectors/verifierauth/token_source.gonew file mode 100644index 000000000..cb1c8ff0e--- /dev/null+++ b/pkg/detectors/verifierauth/token_source.go@@ -0,0 +1,166 @@+package verifierauth++import (+ "context"+ "fmt"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/go-logr/logr"+ "golang.org/x/oauth2"++ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"+)++// defaultTokenLifetime is applied when the identity provider omits+// expires_in from its token response. RFC 6749 makes expires_in optional,+// and oauth2 leaves Expiry zero in that case, which ReuseTokenSource treats+// as "never expires". Without a default, one token would be reused for the+// life of the process and every verification would fail once the IdP+// expired it.+const defaultTokenLifetime = 5 * time.Minute++// ropcTokenSource performs the OAuth2 Resource Owner Password Credentials+// exchange (RFC 6749 section 4.3). It only fetches; caching and refresh are+// layered on top by ReuseTokenSource, and failure backoff by+// tokenErrorCache.+type ropcTokenSource struct {+ conf *oauth2.Config+ username string+ password string+ // client performs the token request. It is deliberately separate from+ // the detector's client: the token endpoint is the identity provider+ // that issues tokens for the auth proxy, not a verification endpoint, so+ // detector-specific transport rules (such as blocking private IPs) do+ // not apply to it.+ client *http.Client+ now func() time.Time+ logger func() logr.Logger+}++// newROPCTokenSource builds an unwrapped ROPC token source. Client+// credentials are sent in the request body (AuthStyleInParams) rather than+// as HTTP basic auth, which is what password-grant deployments of the+// identity providers we target expect.+func newROPCTokenSource(+ tokenEndpoint string,+ ropc *custom_detectorspb.ROPCConfig,+ client *http.Client,+ now func() time.Time,+ logger func() logr.Logger,+) *ropcTokenSource {+ return &ropcTokenSource{+ conf: &oauth2.Config{+ ClientID: ropc.GetClientId(),+ ClientSecret: ropc.GetClientSecret(),+ Endpoint: oauth2.Endpoint{+ TokenURL: tokenEndpoint,+ AuthStyle: oauth2.AuthStyleInParams,+ },+ Scopes: strings.Fields(ropc.GetScope()),+ },+ username: ropc.GetUsername(),+ password: ropc.GetPassword(),+ client: client,+ now: now,+ logger: logger,+ }+}++// Token fetches a new access token.+//+// oauth2.TokenSource.Token takes no context, so the request context is+// rooted in Background and the HTTP client travels on it under the+// oauth2.HTTPClient key, which is how the oauth2 package selects a client.+// The client's timeout is what bounds a hung identity provider.+func (s *ropcTokenSource) Token() (*oauth2.Token, error) {+ ctx := context.WithValue(context.Background(), oauth2.HTTPClient, s.client)++ s.logger().V(2).Info("requesting verifier access token")+ tok, err := s.conf.PasswordCredentialsToken(ctx, s.username, s.password)+ if err != nil {+ return nil, fmt.Errorf("ropc token request failed: %w", err)+ }++ if tok.Expiry.IsZero() {+ tok.Expiry = s.now().Add(defaultTokenLifetime)+ s.logger().V(1).Info("identity provider did not return expires_in; using default token lifetime",+ "default_lifetime", defaultTokenLifetime,+ )+ }+ s.logger().V(1).Info("obtained verifier access token", "expires_at", tok.Expiry)+ return tok, nil+}++// Backoff bounds for tokenErrorCache. The window starts small so a brief+// IdP blip clears quickly, and is capped so that wrong credentials cost at+// most one failed login per maxTokenErrorBackoff, which keeps the scanner+// from tripping the identity provider's account lockout policy.+const (+ minTokenErrorBackoff = 5 * time.Second+ maxTokenErrorBackoff = 5 * time.Minute+)++// tokenErrorCache remembers the most recent token fetch failure and answers+// with it, without contacting the IdP, until a backoff window passes.+// ReuseTokenSource already caches successful tokens; this is the+// counterpart for failures.+//+// It never sleeps. Callers inside a window get the cached error+// immediately, so a failing or hung IdP turns verification for the affected+// auth config into fast "unable to verify" results instead of tying up the+// shared detector worker pool behind token request timeouts. The window+// doubles on each consecutive failure up to maxTokenErrorBackoff and resets+// on the first success.+type tokenErrorCache struct {+ base oauth2.TokenSource+ now func() time.Time+ onFailure func(err error, retryIn time.Duration)++ mu sync.Mutex+ lastErr error+ retryAt time.Time+ window time.Duration+}++func newTokenErrorCache(base oauth2.TokenSource, now func() time.Time, onFailure func(error, time.Duration)) *tokenErrorCache {+ return &tokenErrorCache{base: base, now: now, onFailure: onFailure}+}++// Token returns a fresh token from the base source, or the cached failure+// while a backoff window is open.+//+// The mutex is held across the base fetch so that, when a window expires,+// exactly one caller makes the next attempt and the rest observe its+// outcome. ReuseTokenSource provides the same serialization in production;+// holding the lock here keeps this type correct on its own.+func (c *tokenErrorCache) Token() (*oauth2.Token, error) {+ c.mu.Lock()+ defer c.mu.Unlock()++ if c.lastErr != nil && c.now().Before(c.retryAt) {+ return nil, fmt.Errorf("token fetch failed recently; next attempt after %s: %w",+ c.retryAt.Format(time.RFC3339), c.lastErr)+ }++ tok, err := c.base.Token()+ if err != nil {+ if c.window == 0 {+ c.window = minTokenErrorBackoff+ } else {+ c.window = min(2*c.window, maxTokenErrorBackoff)+ }+ c.lastErr = err+ c.retryAt = c.now().Add(c.window)+ if c.onFailure != nil {+ c.onFailure(err, c.window)+ }+ return nil, err+ }++ c.lastErr = nil+ c.window = 0+ return tok, nil+}diff --git a/pkg/detectors/verifierauth/transport.go b/pkg/detectors/verifierauth/transport.gonew file mode 100644index 000000000..859a214a3--- /dev/null+++ b/pkg/detectors/verifierauth/transport.go@@ -0,0 +1,164 @@+package verifierauth++import (+ "errors"+ "fmt"+ "net"+ "net/http"+ "net/url"+ "strings"+)++// The errors below reach detectors wrapped in *url.Error by http.Client, and+// both are deliberately leaf errors with no Unwrap. Two consumers depend on+// that:+// - Result.SetVerificationError keeps only the innermost error's message,+// so the leaf is what users see as the verification error. It has to+// say "verifier auth" and carry the oauth2_trace for log correlation.+// - Detectors classify request errors to decide that the verification+// host does not exist, by substring ("no such host", "dial tcp") or by+// errors.As into *net.DNSError. An IdP failure must not be mistaken for+// a missing verification host, so the IdP's error is neither in the+// message nor reachable through the chain.++// ErrHeaderCollision reports that a request already carries the header the+// access token would be written to. Built-in detectors commonly send the+// secret under test in Authorization; overwriting it would hand the+// verification service the token instead of the secret and produce wrong+// verdicts, so the request is refused instead. The fix is to set tokenHeader+// to a header the auth proxy reads. Match it with errors.Is.+var ErrHeaderCollision = errors.New("verifier auth token header is already set by the detector; set oauth2 tokenHeader to a different header")++// headerCollisionError is the ErrHeaderCollision instance returned for a+// request, adding the header name and trace to the message.+type headerCollisionError struct {+ header string+ trace string+}++func (e *headerCollisionError) Error() string {+ return fmt.Sprintf("%v (header %q, oauth2_trace=%s)", ErrHeaderCollision, e.header, e.trace)+}++func (e *headerCollisionError) Is(target error) bool { return target == ErrHeaderCollision }++// TokenError reports that no access token could be obtained, so the request+// was not sent. The IdP's error is kept in Err for callers that ask for it+// with errors.As, and every real fetch failure is logged with the same+// oauth2_trace and the token endpoint.+type TokenError struct {+ Trace string+ Err error+}++func (e *TokenError) Error() string {+ return fmt.Sprintf("verifier auth: could not obtain access token (oauth2_trace=%s; see logs for the cause)", e.Trace)+}++// WrapClient returns a copy of base whose transport attaches an access token+// to requests bound for allowedEndpoints. Timeout, redirect policy, and+// cookie jar are carried over from base unchanged; base itself is not+// modified.+//+// Only the scheme and host of each allowed endpoint are matched, because+// detectors append their own API paths to the configured endpoint.+// Requests to any other host pass through without a token. The check runs+// on every round trip, so a redirect to another host never carries the+// token either.+func (c *Config) WrapClient(base *http.Client, allowedEndpoints []string) *http.Client {+ clone := *base+ rt := base.Transport+ if rt == nil {+ rt = http.DefaultTransport+ }+ clone.Transport = &authTransport{+ base: rt,+ cfg: c,+ allowed: originsOf(allowedEndpoints),+ }+ return &clone+}++// originsOf reduces endpoints to their lowercase scheme://host form.+// Endpoints that don't parse as absolute URLs contribute nothing, which+// means no token is ever sent on their behalf.+func originsOf(endpoints []string) map[string]struct{} {+ origins := make(map[string]struct{}, len(endpoints))+ for _, endpoint := range endpoints {+ u, err := url.Parse(endpoint)+ if err != nil || u.Scheme == "" || u.Host == "" {+ continue+ }+ origins[origin(u)] = struct{}{}+ }+ return origins+}++// defaultPorts maps each scheme a verifier endpoint may use to the port it+// implies when the URL names none.+var defaultPorts = map[string]string{"http": "80", "https": "443"}++// origin reduces u to the lowercase scheme://host[:port] key used for the+// allowlist. url.URL keeps the host exactly as written, so the same server+// can arrive as "https://h" or "https://h:443": the configured endpoint and+// a detector's rebuilt request URL need not agree on spelling. The default+// port for the scheme is dropped so both forms produce one key; dropping it+// (rather than always adding it) matches how endpoints are usually written.+// Non-default ports are kept, so "https://h:8443" stays a different origin.+func origin(u *url.URL) string {+ scheme := strings.ToLower(u.Scheme)+ host := strings.ToLower(u.Hostname())+ if port := u.Port(); port != "" && port != defaultPorts[scheme] {+ host = net.JoinHostPort(host, port)+ } else if strings.Contains(host, ":") {+ // Hostname strips the brackets from an IPv6 literal, and+ // JoinHostPort only restores them when there is a port.+ host = "[" + host + "]"+ }+ return scheme + "://" + host+}++// authTransport attaches the access token to requests for allowed origins.+type authTransport struct {+ base http.RoundTripper+ cfg *Config+ allowed map[string]struct{}+}++// RoundTrip attaches the token and forwards the request, or fails it+// without sending anything. Every failure is returned as a request error,+// which detectors already report as a verification error, never as "not+// verified".+//+// The token is set on a clone because a RoundTripper must not modify the+// caller's request. That also keeps the token off the request http.Client+// reuses to build redirects; each redirect hop comes back through here and+// is checked against the allowlist again.+func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ if _, ok := t.allowed[origin(req.URL)]; !ok {+ return t.base.RoundTrip(req)+ }++ if len(req.Header.Values(t.cfg.tokenHeader)) > 0 {+ closeBody(req)+ return nil, &headerCollisionError{header: t.cfg.tokenHeader, trace: t.cfg.trace}+ }++ tok, err := t.cfg.tokens.Token()+ if err != nil {+ closeBody(req)+ return nil, &TokenError{Trace: t.cfg.trace, Err: err}+ }++ authed := req.Clone(req.Context())+ authed.Header.Set(t.cfg.tokenHeader, "Bearer "+tok.AccessToken)+ return t.base.RoundTrip(authed)+}++// closeBody honors the RoundTripper contract that the request body is+// closed even when RoundTrip returns an error without sending.+func closeBody(req *http.Request) {+ if req.Body != nil {+ _ = req.Body.Close()+ }+}diff --git a/pkg/detectors/verifierauth/verifierauth.go b/pkg/detectors/verifierauth/verifierauth.gonew file mode 100644index 000000000..3eaa0a70f--- /dev/null+++ b/pkg/detectors/verifierauth/verifierauth.go@@ -0,0 +1,148 @@+// Package verifierauth authenticates verification requests to endpoints that+// sit behind an auth proxy: an OAuth-protected component in front of a+// verification service that requires an access token before it forwards a+// request to that service.+//+// Authentication is purely an HTTP-client concern. A Config wraps a+// detector's existing *http.Client so every request to a configured endpoint+// carries an access token, while the detector keeps full ownership of its+// request shape and of how responses map to verdicts. The wrapper never+// decides "verified" or "not verified"; it either attaches a token or fails+// the request, and a failed request surfaces as a verification error+// ("unable to verify").+//+// The package sits below pkg/detectors so that both pkg/detectors+// (EndpointSetter, used by built-in detectors) and pkg/custom_detectors can+// use it. It must never import either of them.+package verifierauth++import (+ "errors"+ "fmt"+ "net/http"+ "strings"+ "time"++ "github.com/go-logr/logr"+ "github.com/google/uuid"+ "golang.org/x/net/http/httpguts"+ "golang.org/x/oauth2"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"+)++// DefaultTokenHeader is the header that carries the access token when the+// configuration does not name one.+const DefaultTokenHeader = "Authorization"++// Config is a validated, ready-to-use verifier authentication setup. One+// Config is shared by every request (and every detector worker) that uses+// the same auth block, so its token cache and token error cache are shared+// too. A nil *Config means "no auth configured".+type Config struct {+ tokens oauth2.TokenSource+ tokenHeader string+ tokenEndpoint string+ // trace correlates every log line and error produced for this auth+ // config, so an operator can follow one auth block from token fetch+ // through to the verification requests that used it.+ trace string+}++// FromProto validates an auth block and builds a Config from it. It returns+// (nil, nil) when auth is nil, so callers can pass the field through+// unconditionally.+//+// No token is fetched here. Token acquisition is deferred to the first+// verification request that needs one, so an unreachable identity provider+// degrades verification for the affected detector instead of failing+// startup, and the rest of the scan proceeds. Only the structure of the+// config is checked up front.+//+// unsafe has the same meaning as on VerifierConfig: it permits a plain+// http:// token endpoint.+func FromProto(auth *custom_detectorspb.VerifierAuth, unsafe bool) (*Config, error) {+ if auth == nil {+ return nil, nil+ }+ oc := auth.GetOauth2()+ if oc == nil {+ return nil, errors.New("auth is set but names no auth mechanism (expected oauth2)")+ }+ if err := ValidateEndpoint(oc.GetTokenEndpoint(), unsafe); err != nil {+ return nil, fmt.Errorf("oauth2 tokenEndpoint: %w", err)+ }++ tokenHeader := oc.GetTokenHeader()+ if tokenHeader == "" {+ tokenHeader = DefaultTokenHeader+ }+ if !httpguts.ValidHeaderFieldName(tokenHeader) {+ return nil, fmt.Errorf("oauth2 tokenHeader %q is not a valid HTTP header name", tokenHeader)+ }++ ropc := oc.GetRopc()+ if ropc == nil {+ return nil, errors.New("oauth2 auth names no grant (expected ropc)")+ }+ switch {+ case ropc.GetUsername() == "":+ return nil, errors.New("oauth2 ropc username is required")+ case ropc.GetPassword() == "":+ return nil, errors.New("oauth2 ropc password is required")+ case ropc.GetClientId() == "":+ return nil, errors.New("oauth2 ropc clientId is required")+ }++ cfg := &Config{+ tokenHeader: http.CanonicalHeaderKey(tokenHeader),+ tokenEndpoint: oc.GetTokenEndpoint(),+ trace: uuid.NewString(),+ }+ base := newROPCTokenSource(oc.GetTokenEndpoint(), ropc, common.SaneHttpClient(), time.Now, cfg.logger)+ errCache := newTokenErrorCache(base, time.Now, func(err error, retryIn time.Duration) {+ cfg.logger().Error(err, "failed to obtain verifier access token; verification for this auth config is unavailable until the retry",+ "retry_in", retryIn,+ )+ })+ // ReuseTokenSource caches the token and refreshes it shortly before it+ // expires. It serializes callers on its own lock while a fetch is in+ // flight, so concurrent detector workers trigger at most one fetch.+ cfg.tokens = oauth2.ReuseTokenSource(nil, errCache)+ return cfg, nil+}++// TokenHeader reports the canonical header name that carries the token.+// Callers that build requests from user-supplied headers use it to reject a+// configuration that would collide with the token at load time.+func (c *Config) TokenHeader() string {+ return c.tokenHeader+}++// logger returns a logger tagged with this config's trace ID. It resolves+// the default logger at call time rather than at construction, so log+// output follows whatever logger the process configured after startup.+func (c *Config) logger() logr.Logger {+ return logContext.Background().Logger().WithValues(+ "oauth2_trace", c.trace,+ "token_endpoint", c.tokenEndpoint,+ )+}++// ValidateEndpoint enforces the transport rule shared by verification+// endpoints and token endpoints: the endpoint must be set, and plain http://+// is only allowed when the verifier is explicitly marked unsafe. It lives+// here, rather than in pkg/custom_detectors, so this package can apply the+// same rule to token endpoints without importing custom_detectors.+func ValidateEndpoint(endpoint string, unsafe bool) error {+ if len(endpoint) == 0 {+ return fmt.Errorf("no endpoint")+ }++ if strings.HasPrefix(endpoint, "http://") && !unsafe {+ return fmt.Errorf("http endpoint must have unsafe=true")+ }+ return nil+}diff --git a/pkg/detectors/verifierauth/verifierauth_test.go b/pkg/detectors/verifierauth/verifierauth_test.gonew file mode 100644index 000000000..d1688ff35--- /dev/null+++ b/pkg/detectors/verifierauth/verifierauth_test.go@@ -0,0 +1,661 @@+package verifierauth++import (+ "encoding/json"+ "errors"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "net/url"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/go-logr/logr"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "golang.org/x/oauth2"++ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"+)++// fakeIdP is a token endpoint that records each token request and answers+// with a configurable response.+type fakeIdP struct {+ *httptest.Server+ hits atomic.Int32+ mu sync.Mutex+ forms []url.Values+ headers []http.Header+ status int+ response map[string]any+}++func newFakeIdP(t *testing.T) *fakeIdP {+ t.Helper()+ idp := &fakeIdP{+ status: http.StatusOK,+ response: map[string]any{"access_token": "idp-token", "token_type": "Bearer", "expires_in": 3600},+ }+ idp.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ idp.hits.Add(1)+ _ = r.ParseForm()+ idp.mu.Lock()+ idp.forms = append(idp.forms, r.PostForm)+ idp.headers = append(idp.headers, r.Header.Clone())+ status, response := idp.status, idp.response+ idp.mu.Unlock()++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(response)+ }))+ t.Cleanup(idp.Close)+ return idp+}++func (idp *fakeIdP) lastForm(t *testing.T) url.Values {+ t.Helper()+ idp.mu.Lock()+ defer idp.mu.Unlock()+ require.NotEmpty(t, idp.forms)+ return idp.forms[len(idp.forms)-1]+}++// recordingServer is a verification endpoint that records the headers of+// each request it receives.+type recordingServer struct {+ *httptest.Server+ mu sync.Mutex+ headers []http.Header+}++func newRecordingServer(t *testing.T, handler http.HandlerFunc) *recordingServer {+ t.Helper()+ rs := &recordingServer{}+ rs.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rs.mu.Lock()+ rs.headers = append(rs.headers, r.Header.Clone())+ rs.mu.Unlock()+ if handler != nil {+ handler(w, r)+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(rs.Close)+ return rs+}++func (rs *recordingServer) requests() []http.Header {+ rs.mu.Lock()+ defer rs.mu.Unlock()+ return append([]http.Header(nil), rs.headers...)+}++func ropcAuth(tokenEndpoint, tokenHeader string) *custom_detectorspb.VerifierAuth {+ return &custom_detectorspb.VerifierAuth{+ AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{+ Oauth2: &custom_detectorspb.OAuth2Config{+ TokenEndpoint: tokenEndpoint,+ TokenHeader: tokenHeader,+ GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{+ Ropc: &custom_detectorspb.ROPCConfig{+ Username: "svc-scanner",+ Password: "hunter2",+ ClientId: "scanner-client",+ ClientSecret: "client-secret",+ Scope: "verify",+ },+ },+ },+ },+ }+}++func mustConfig(t *testing.T, auth *custom_detectorspb.VerifierAuth) *Config {+ t.Helper()+ // The fake IdP is plain HTTP, so these tests opt into unsafe.+ cfg, err := FromProto(auth, true)+ require.NoError(t, err)+ require.NotNil(t, cfg)+ return cfg+}++// get sends a GET through client and drains and closes any response body+// itself. Only the request error is returned, because the tests assert on+// what the servers recorded rather than on the response.+func get(t *testing.T, client *http.Client, target string, header http.Header) error {+ t.Helper()+ req, err := http.NewRequest(http.MethodGet, target, nil)+ require.NoError(t, err)+ for k, vs := range header {+ for _, v := range vs {+ req.Header.Add(k, v)+ }+ }+ resp, err := client.Do(req)+ if resp != nil {+ _, _ = io.Copy(io.Discard, resp.Body)+ _ = resp.Body.Close()+ }+ return err+}++func TestFromProto_NilAuthMeansNoAuth(t *testing.T) {+ cfg, err := FromProto(nil, false)+ assert.NoError(t, err)+ assert.Nil(t, cfg)+}++func TestFromProto_RejectsInvalidConfig(t *testing.T) {+ withRopc := func(mutate func(*custom_detectorspb.ROPCConfig)) *custom_detectorspb.VerifierAuth {+ auth := ropcAuth("https://idp.example.com/token", "")+ mutate(auth.GetOauth2().GetRopc())+ return auth+ }++ tests := []struct {+ name string+ auth *custom_detectorspb.VerifierAuth+ unsafe bool+ }{+ {name: "no mechanism", auth: &custom_detectorspb.VerifierAuth{}},+ {name: "empty token endpoint", auth: ropcAuth("", "")},+ {name: "http token endpoint without unsafe", auth: ropcAuth("http://idp.example.com/token", "")},+ {name: "invalid token header", auth: ropcAuth("https://idp.example.com/token", "Bad Header")},+ {+ name: "no grant",+ auth: &custom_detectorspb.VerifierAuth{AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{+ Oauth2: &custom_detectorspb.OAuth2Config{TokenEndpoint: "https://idp.example.com/token"},+ }},+ },+ {name: "missing username", auth: withRopc(func(r *custom_detectorspb.ROPCConfig) { r.Username = "" })},+ {name: "missing password", auth: withRopc(func(r *custom_detectorspb.ROPCConfig) { r.Password = "" })},+ {name: "missing client id", auth: withRopc(func(r *custom_detectorspb.ROPCConfig) { r.ClientId = "" })},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ cfg, err := FromProto(tt.auth, tt.unsafe)+ assert.Error(t, err)+ assert.Nil(t, cfg)+ })+ }+}++func TestFromProto_AllowsHTTPTokenEndpointWhenUnsafe(t *testing.T) {+ cfg, err := FromProto(ropcAuth("http://idp.example.com/token", ""), true)+ assert.NoError(t, err)+ assert.NotNil(t, cfg)+}++func TestFromProto_TokenHeaderDefaultsToAuthorizationAndIsCanonicalized(t *testing.T) {+ cfg := mustConfig(t, ropcAuth("https://idp.example.com/token", ""))+ assert.Equal(t, "Authorization", cfg.TokenHeader())++ cfg = mustConfig(t, ropcAuth("https://idp.example.com/token", "x-auth-proxy-token"))+ assert.Equal(t, "X-Auth-Proxy-Token", cfg.TokenHeader())+}++func TestFromProto_DoesNotFetchATokenUpFront(t *testing.T) {+ idp := newFakeIdP(t)+ mustConfig(t, ropcAuth(idp.URL, ""))+ assert.Zero(t, idp.hits.Load())+}++func TestROPCTokenSource_SendsPasswordGrantWithClientCredentialsInBody(t *testing.T) {+ idp := newFakeIdP(t)+ ropc := ropcAuth(idp.URL, "").GetOauth2().GetRopc()+ ts := newROPCTokenSource(idp.URL, ropc, idp.Client(), time.Now, logr.Discard)++ tok, err := ts.Token()+ require.NoError(t, err)+ assert.Equal(t, "idp-token", tok.AccessToken)++ form := idp.lastForm(t)+ assert.Equal(t, "password", form.Get("grant_type"))+ assert.Equal(t, "svc-scanner", form.Get("username"))+ assert.Equal(t, "hunter2", form.Get("password"))+ assert.Equal(t, "scanner-client", form.Get("client_id"))+ assert.Equal(t, "client-secret", form.Get("client_secret"))+ assert.Equal(t, "verify", form.Get("scope"))+ assert.Empty(t, idp.headers[0].Get("Authorization"), "client credentials must not be sent as basic auth")+}++func TestROPCTokenSource_ScopeHandling(t *testing.T) {+ tests := []struct {+ name string+ scope string+ wantScope string+ wantSent bool+ }{+ {name: "multiple scopes are space separated", scope: "read write", wantScope: "read write", wantSent: true},+ {name: "empty scope sends no scope parameter", scope: "", wantSent: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ idp := newFakeIdP(t)+ ropc := ropcAuth(idp.URL, "").GetOauth2().GetRopc()+ ropc.Scope = tt.scope+ ts := newROPCTokenSource(idp.URL, ropc, idp.Client(), time.Now, logr.Discard)++ _, err := ts.Token()+ require.NoError(t, err)+ form := idp.lastForm(t)+ assert.Equal(t, tt.wantSent, form.Has("scope"))+ assert.Equal(t, tt.wantScope, form.Get("scope"))+ })+ }+}++func TestROPCTokenSource_DefaultExpiryWhenIdPOmitsExpiresIn(t *testing.T) {+ idp := newFakeIdP(t)+ idp.response = map[string]any{"access_token": "idp-token", "token_type": "Bearer"}+ now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)+ ropc := ropcAuth(idp.URL, "").GetOauth2().GetRopc()+ ts := newROPCTokenSource(idp.URL, ropc, idp.Client(), func() time.Time { return now }, logr.Discard)++ tok, err := ts.Token()+ require.NoError(t, err)+ assert.Equal(t, now.Add(defaultTokenLifetime), tok.Expiry)+}++func TestROPCTokenSource_ReturnsErrorOnRejectedCredentials(t *testing.T) {+ idp := newFakeIdP(t)+ idp.status = http.StatusUnauthorized+ idp.response = map[string]any{"error": "invalid_grant"}+ ropc := ropcAuth(idp.URL, "").GetOauth2().GetRopc()+ ts := newROPCTokenSource(idp.URL, ropc, idp.Client(), time.Now, logr.Discard)++ _, err := ts.Token()+ assert.Error(t, err)+}++func TestConfig_ReusesTokenUntilNearExpiry(t *testing.T) {+ tests := []struct {+ name string+ expiresIn int+ wantHits int32+ }{+ // ReuseTokenSource refreshes 10 seconds before expiry, so a token that+ // expires within that margin is treated as already stale.+ {name: "long-lived token is reused", expiresIn: 3600, wantHits: 1},+ {name: "token inside the refresh margin is refetched", expiresIn: 1, wantHits: 2},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ idp := newFakeIdP(t)+ idp.response = map[string]any{"access_token": "idp-token", "token_type": "Bearer", "expires_in": tt.expiresIn}+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ for range 2 {+ err := get(t, client, verifier.URL+"/check", nil)+ require.NoError(t, err)+ }+ assert.Equal(t, tt.wantHits, idp.hits.Load())+ })+ }+}++func TestWrapClient_AttachesBearerTokenInDefaultHeader(t *testing.T) {+ idp := newFakeIdP(t)+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL + "/base/path"})++ err := get(t, client, verifier.URL+"/other/path", nil)+ require.NoError(t, err)++ reqs := verifier.requests()+ require.Len(t, reqs, 1)+ assert.Equal(t, "Bearer idp-token", reqs[0].Get("Authorization"))+}++func TestWrapClient_CustomTokenHeaderLeavesDetectorAuthorizationUntouched(t *testing.T) {+ idp := newFakeIdP(t)+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, "X-Auth-Proxy-Token"))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ err := get(t, client, verifier.URL, http.Header{"Authorization": {"Bearer secret-under-test"}})+ require.NoError(t, err)++ reqs := verifier.requests()+ require.Len(t, reqs, 1)+ assert.Equal(t, "Bearer secret-under-test", reqs[0].Get("Authorization"))+ assert.Equal(t, "Bearer idp-token", reqs[0].Get("X-Auth-Proxy-Token"))+}++func TestWrapClient_DoesNotAttachTokenToOtherHosts(t *testing.T) {+ idp := newFakeIdP(t)+ allowed := newRecordingServer(t, nil)+ other := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, "X-Auth-Proxy-Token"))+ client := cfg.WrapClient(http.DefaultClient, []string{allowed.URL})++ err := get(t, client, other.URL, nil)+ require.NoError(t, err)++ reqs := other.requests()+ require.Len(t, reqs, 1)+ assert.Empty(t, reqs[0].Get("X-Auth-Proxy-Token"))+ assert.Zero(t, idp.hits.Load(), "no token is needed for a host outside the allowlist")+}++func TestWrapClient_DoesNotCarryTokenAcrossRedirectToAnotherHost(t *testing.T) {+ idp := newFakeIdP(t)+ elsewhere := newRecordingServer(t, nil)+ allowed := newRecordingServer(t, func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, elsewhere.URL+"/landing", http.StatusFound)+ })+ cfg := mustConfig(t, ropcAuth(idp.URL, "X-Auth-Proxy-Token"))+ client := cfg.WrapClient(http.DefaultClient, []string{allowed.URL})++ err := get(t, client, allowed.URL, nil)+ require.NoError(t, err)++ require.Len(t, allowed.requests(), 1)+ assert.Equal(t, "Bearer idp-token", allowed.requests()[0].Get("X-Auth-Proxy-Token"))+ require.Len(t, elsewhere.requests(), 1)+ assert.Empty(t, elsewhere.requests()[0].Get("X-Auth-Proxy-Token"))+}++// headerCapture is a RoundTripper that records the headers of the request it+// is given and answers 200 without touching the network, so tests can use+// hosts and default ports that no local server listens on.+type headerCapture struct{ got http.Header }++func (c *headerCapture) RoundTrip(req *http.Request) (*http.Response, error) {+ c.got = req.Header.Clone()+ return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Request: req}, nil+}++func TestWrapClient_MatchesOriginsRegardlessOfDefaultPortSpelling(t *testing.T) {+ tests := []struct {+ name string+ configured string+ request string+ wantToken bool+ }{+ {name: "https endpoint written with :443", configured: "https://proxy.example.com:443/base", request: "https://proxy.example.com/api", wantToken: true},+ {name: "https request written with :443", configured: "https://proxy.example.com/base", request: "https://proxy.example.com:443/api", wantToken: true},+ {name: "http endpoint written with :80", configured: "http://proxy.example.com:80", request: "http://proxy.example.com/api", wantToken: true},+ {name: "http request written with :80", configured: "http://proxy.example.com", request: "http://proxy.example.com:80/api", wantToken: true},+ {name: "IPv6 literal with default port", configured: "https://[2001:db8::1]:443", request: "https://[2001:db8::1]/api", wantToken: true},+ {name: "IPv6 literal with non-default port", configured: "https://[2001:db8::1]:8443", request: "https://[2001:db8::1]:8443/api", wantToken: true},+ {name: "non-default port must match exactly", configured: "https://proxy.example.com:8443", request: "https://proxy.example.com/api", wantToken: false},+ {name: "another scheme's default port is a different origin", configured: "https://proxy.example.com", request: "https://proxy.example.com:80/api", wantToken: false},+ {name: "http never matches an https endpoint", configured: "https://proxy.example.com", request: "http://proxy.example.com/api", wantToken: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ idp := newFakeIdP(t)+ capture := &headerCapture{}+ cfg := mustConfig(t, ropcAuth(idp.URL, "X-Auth-Proxy-Token"))+ client := cfg.WrapClient(&http.Client{Transport: capture}, []string{tt.configured})++ err := get(t, client, tt.request, nil)+ require.NoError(t, err)++ if tt.wantToken {+ assert.Equal(t, "Bearer idp-token", capture.got.Get("X-Auth-Proxy-Token"))+ } else {+ assert.Empty(t, capture.got.Get("X-Auth-Proxy-Token"))+ }+ })+ }+}++func TestWrapClient_RefusesToOverwriteHeaderSetByDetector(t *testing.T) {+ idp := newFakeIdP(t)+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ err := get(t, client, verifier.URL, http.Header{"Authorization": {"Bearer secret-under-test"}})+ require.Error(t, err)+ assert.ErrorIs(t, err, ErrHeaderCollision)+ assert.Empty(t, verifier.requests(), "a colliding request must not be sent")+ assert.Zero(t, idp.hits.Load())+}++func TestWrapClient_TokenFailureFailsRequestWithoutSending(t *testing.T) {+ idp := newFakeIdP(t)+ idp.status = http.StatusUnauthorized+ idp.response = map[string]any{"error": "invalid_grant"}+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ err := get(t, client, verifier.URL, nil)+ var tokenErr *TokenError+ require.ErrorAs(t, err, &tokenErr)+ assert.Equal(t, cfg.trace, tokenErr.Trace)+ var retrieveErr *oauth2.RetrieveError+ assert.ErrorAs(t, tokenErr.Err, &retrieveErr, "the IdP's response is kept for callers that ask for it")+ assert.Empty(t, verifier.requests())+}++// Result.SetVerificationError reports only the innermost error of the chain+// http.Client returns, so that error must be the one naming verifier auth.+func TestWrapClient_AuthErrorsAreTheInnermostErrorOfTheRequestError(t *testing.T) {+ idp := newFakeIdP(t)+ idp.status = http.StatusUnauthorized+ idp.response = map[string]any{"error": "invalid_grant"}+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ innermost := func(err error) error {+ for errors.Unwrap(err) != nil {+ err = errors.Unwrap(err)+ }+ return err+ }++ err := get(t, client, verifier.URL, nil)+ assert.IsType(t, &TokenError{}, innermost(err))++ err = get(t, client, verifier.URL, http.Header{"Authorization": {"Bearer secret-under-test"}})+ leaf := innermost(err)+ assert.ErrorIs(t, leaf, ErrHeaderCollision)+ assert.Contains(t, leaf.Error(), `header "Authorization"`)+ assert.Contains(t, leaf.Error(), "oauth2_trace="+cfg.trace)+}++// Detectors read "dial tcp" or "no such host" in a request error, or a+// *net.DNSError in its chain, as "the verification host does not exist".+// An unreachable IdP must not trip those checks.+func TestWrapClient_UnreachableIdPErrorDoesNotLookLikeMissingVerificationHost(t *testing.T) {+ idp := newFakeIdP(t)+ idpURL := idp.URL+ idp.Close()+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idpURL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ err := get(t, client, verifier.URL, nil)+ var tokenErr *TokenError+ require.ErrorAs(t, err, &tokenErr)+ require.ErrorContains(t, tokenErr.Err, "dial tcp", "precondition: the cause is a network error")+ for _, marker := range []string{"no such host", "dial tcp", "connection refused"} {+ assert.NotContains(t, err.Error(), marker)+ }+ var opErr *net.OpError+ assert.False(t, errors.As(err, &opErr), "the IdP's network error must not be reachable through the chain")+ assert.Empty(t, verifier.requests())+}++func TestWrapClient_RepeatedTokenFailuresAreAnsweredFromCache(t *testing.T) {+ idp := newFakeIdP(t)+ idp.status = http.StatusUnauthorized+ idp.response = map[string]any{"error": "invalid_grant"}+ verifier := newRecordingServer(t, nil)+ cfg := mustConfig(t, ropcAuth(idp.URL, ""))+ client := cfg.WrapClient(verifier.Client(), []string{verifier.URL})++ for range 3 {+ err := get(t, client, verifier.URL, nil)+ assert.Error(t, err)+ }+ assert.Equal(t, int32(1), idp.hits.Load(), "failures inside the backoff window must not reach the IdP")+}++func TestWrapClient_DoesNotModifyBaseClient(t *testing.T) {+ base := &http.Client{Timeout: 7 * time.Second}+ cfg := mustConfig(t, ropcAuth("https://idp.example.com/token", ""))++ wrapped := cfg.WrapClient(base, []string{"https://verify.example.com"})+ assert.Nil(t, base.Transport)+ assert.Equal(t, 7*time.Second, wrapped.Timeout)+ assert.NotSame(t, base, wrapped)+}++// fakeClock is a manually advanced clock for tokenErrorCache tests.+type fakeClock struct {+ mu sync.Mutex+ now time.Time+}++func (c *fakeClock) Now() time.Time {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.now+}++func (c *fakeClock) Advance(d time.Duration) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.now = c.now.Add(d)+}++// scriptedSource returns err (when non-nil) or a token, counting calls.+type scriptedSource struct {+ calls atomic.Int32+ mu sync.Mutex+ err error+ gate chan struct{}+}++func (s *scriptedSource) Token() (*oauth2.Token, error) {+ s.calls.Add(1)+ if s.gate != nil {+ <-s.gate+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.err != nil {+ return nil, s.err+ }+ return &oauth2.Token{AccessToken: "tok"}, nil+}++func (s *scriptedSource) setErr(err error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.err = err+}++func TestTokenErrorCache_ReturnsCachedFailureWithinWindow(t *testing.T) {+ clock := &fakeClock{now: time.Unix(0, 0)}+ errIdP := errors.New("idp down")+ base := &scriptedSource{err: errIdP}+ cache := newTokenErrorCache(base, clock.Now, nil)++ _, err := cache.Token()+ require.ErrorIs(t, err, errIdP)++ clock.Advance(minTokenErrorBackoff - time.Second)+ _, err = cache.Token()+ assert.ErrorIs(t, err, errIdP, "cached error keeps the original cause")+ assert.Equal(t, int32(1), base.calls.Load())+}++func TestTokenErrorCache_RetriesAfterWindow(t *testing.T) {+ clock := &fakeClock{now: time.Unix(0, 0)}+ base := &scriptedSource{err: errors.New("idp down")}+ cache := newTokenErrorCache(base, clock.Now, nil)++ _, _ = cache.Token()+ clock.Advance(minTokenErrorBackoff)+ base.setErr(nil)++ tok, err := cache.Token()+ require.NoError(t, err)+ assert.Equal(t, "tok", tok.AccessToken)+ assert.Equal(t, int32(2), base.calls.Load())+}++func TestTokenErrorCache_WindowDoublesAndStopsAtCap(t *testing.T) {+ clock := &fakeClock{now: time.Unix(0, 0)}+ base := &scriptedSource{err: errors.New("idp down")}+ var windows []time.Duration+ cache := newTokenErrorCache(base, clock.Now, func(_ error, retryIn time.Duration) {+ windows = append(windows, retryIn)+ })++ for range 9 {+ _, _ = cache.Token()+ clock.Advance(maxTokenErrorBackoff)+ }++ assert.Equal(t, []time.Duration{+ 5 * time.Second, 10 * time.Second, 20 * time.Second, 40 * time.Second, 80 * time.Second,+ 160 * time.Second, 5 * time.Minute, 5 * time.Minute, 5 * time.Minute,+ }, windows)+}++func TestTokenErrorCache_SuccessResetsWindow(t *testing.T) {+ clock := &fakeClock{now: time.Unix(0, 0)}+ base := &scriptedSource{err: errors.New("idp down")}+ var windows []time.Duration+ cache := newTokenErrorCache(base, clock.Now, func(_ error, retryIn time.Duration) {+ windows = append(windows, retryIn)+ })++ _, _ = cache.Token()+ clock.Advance(maxTokenErrorBackoff)+ _, _ = cache.Token()+ clock.Advance(maxTokenErrorBackoff)++ base.setErr(nil)+ _, err := cache.Token()+ require.NoError(t, err)++ base.setErr(errors.New("idp down again"))+ _, _ = cache.Token()+ assert.Equal(t, []time.Duration{5 * time.Second, 10 * time.Second, 5 * time.Second}, windows)+}++func TestTokenErrorCache_ConcurrentCallersDuringFailureMakeOneFetch(t *testing.T) {+ clock := &fakeClock{now: time.Unix(0, 0)}+ gate := make(chan struct{})+ base := &scriptedSource{err: errors.New("idp down"), gate: gate}+ cache := newTokenErrorCache(base, clock.Now, nil)++ const callers = 20+ var wg sync.WaitGroup+ errs := make(chan error, callers)+ for range callers {+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := cache.Token()+ errs <- err+ }()+ }+ // Let the single in-flight fetch fail; every other caller is queued on+ // the cache lock and then sees the open backoff window.+ close(gate)+ wg.Wait()+ close(errs)++ for err := range errs {+ assert.Error(t, err)+ }+ assert.Equal(t, int32(1), base.calls.Load())+}diff --git a/pkg/detectors/verifierauth/verifierauthtest/verifierauthtest.go b/pkg/detectors/verifierauth/verifierauthtest/verifierauthtest.gonew file mode 100644index 000000000..5c39b641f--- /dev/null+++ b/pkg/detectors/verifierauth/verifierauthtest/verifierauthtest.go@@ -0,0 +1,83 @@+// Package verifierauthtest supports tests outside verifierauth that exercise+// the verifier auth path: a fake OAuth2 identity provider that issues a fixed+// access token, and a helper that builds a verifierauth.Config against it.+// It is imported only from tests, so it never ends up in the binary.+package verifierauthtest++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"++ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"+)++// AccessToken is the access token the fake IdP issues. Verification servers+// in tests expect it as "Bearer " + AccessToken in the configured header.+const AccessToken = "auth-proxy-access-token"++// IdP is a fake OAuth2 token endpoint for the ROPC grant. It answers every+// token request with AccessToken until RejectCredentials is called.+type IdP struct {+ *httptest.Server+ hits atomic.Int32+ rejected atomic.Bool+}++// NewIdP starts a fake IdP that is closed when the test ends.+func NewIdP(t testing.TB) *IdP {+ t.Helper()+ idp := &IdP{}+ idp.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ idp.hits.Add(1)+ w.Header().Set("Content-Type", "application/json")+ if idp.rejected.Load() {+ w.WriteHeader(http.StatusUnauthorized)+ _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant"})+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "access_token": AccessToken,+ "token_type": "Bearer",+ "expires_in": 3600,+ })+ }))+ t.Cleanup(idp.Close)+ return idp+}++// RejectCredentials makes every later token request fail with invalid_grant,+// which is how an IdP answers wrong service account credentials.+func (idp *IdP) RejectCredentials() { idp.rejected.Store(true) }++// Hits reports how many token requests the IdP has received.+func (idp *IdP) Hits() int { return int(idp.hits.Load()) }++// Config builds a verifier auth config that fetches tokens from idp and+// writes them to tokenHeader (empty means the default, Authorization). The+// fake IdP is plain HTTP, so the config is built with unsafe set.+func Config(t testing.TB, idp *IdP, tokenHeader string) *verifierauth.Config {+ t.Helper()+ cfg, err := verifierauth.FromProto(&custom_detectorspb.VerifierAuth{+ AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{+ Oauth2: &custom_detectorspb.OAuth2Config{+ TokenEndpoint: idp.URL,+ TokenHeader: tokenHeader,+ GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{+ Ropc: &custom_detectorspb.ROPCConfig{+ Username: "svc-scanner",+ Password: "svc-password",+ ClientId: "scanner-client",+ },+ },+ },+ },+ }, true)+ if err != nil {+ t.Fatalf("building verifier auth config: %v", err)+ }+ return cfg+}diff --git a/pkg/engine/engine.go b/pkg/engine/engine.goindex 408496a80..6764b5a89 100644--- a/pkg/engine/engine.go+++ b/pkg/engine/engine.go@@ -25,6 +25,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/decoders""github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth""github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick""github.com/trufflesecurity/trufflehog/v3/pkg/engine/defaults""github.com/trufflesecurity/trufflehog/v3/pkg/giturl"@@ -111,6 +112,15 @@ type Config struct {CustomVerifiersOnly boolVerifierEndpoints map[string]string+ // VerifierAuth authenticates verification requests to custom verifier+ // endpoints that sit behind an auth proxy. It is keyed like the parsed+ // VerifierEndpoints, and every entry must have a matching+ // VerifierEndpoints entry: auth only ever applies to configured+ // endpoints. Detectors receive it through VerifierAuthCustomizer and+ // attach the token inside their own HTTP client, so verification still+ // runs through each detector's FromData.+ VerifierAuth map[config.DetectorID]*verifierauth.Config+// Verify determines whether the scanner will verify candidate secrets.Verify bool@@ -306,6 +316,12 @@ func NewEngine(ctx context.Context, cfg *Config) (*Engine, error) {if err != nil {return nil, err}+ // Auth misconfiguration is checked before any filter runs, because a+ // filter can only keep or drop a detector. Dropping a detector whose auth+ // can't be applied would silently remove it from the scan.+ if err := validateVerifierAuth(cfg.VerifierAuth, detectorsWithCustomVerifierEndpoints); err != nil {+ return nil, err+ }if len(detectorsWithCustomVerifierEndpoints) > 0 {filters = append(filters, func(d detectors.Detector) bool {urls, ok := getWithDetectorID(d, detectorsWithCustomVerifierEndpoints)@@ -326,6 +342,17 @@ func NewEngine(ctx context.Context, cfg *Config) (*Engine, error) {return false}+ // validateVerifierAuth has already confirmed this detector type+ // supports auth, so the type assertion only fails for a detector+ // instance that diverges from its registered default.+ if authCfg, ok := getWithDetectorID(d, cfg.VerifierAuth); ok && authCfg != nil {+ authCustomizer, ok := d.(detectors.VerifierAuthCustomizer)+ if !ok {+ return false+ }+ authCustomizer.SetVerifierAuth(authCfg)+ }+return true})}@@ -453,6 +480,30 @@ func parseCustomVerifierEndpoints(endpoints map[string]string) (map[config.Detecreturn customVerifierEndpoints, nil}+// validateVerifierAuth rejects verifier auth that could not take effect:+// auth for a detector with no custom verifier endpoints (auth only ever+// applies to configured endpoints) and auth for a detector type that cannot+// accept it. Either would otherwise send requests to the auth proxy without+// the token, which typically reads as every secret being unverified.+func validateVerifierAuth(auth map[config.DetectorID]*verifierauth.Config, endpoints map[config.DetectorID][]string) error {+ if len(auth) == 0 {+ return nil+ }+ supportsAuth := defaults.DefaultDetectorTypesImplementing[detectors.VerifierAuthCustomizer]()+ for id, authCfg := range auth {+ if authCfg == nil {+ continue+ }+ if _, ok := endpoints[id]; !ok {+ return fmt.Errorf("verifier auth configured for detector %q without custom verifier endpoints", id.String())+ }+ if _, ok := supportsAuth[id.ID]; !ok {+ return fmt.Errorf("verifier auth configured for detector %q, which does not support verifier auth", id.String())+ }+ }+ return nil+}+// detectorTypeToSet is a helper function to convert a slice of detector IDs into a set.func detectorTypeToSet(detectors []config.DetectorID) map[config.DetectorID]struct{} {out := make(map[config.DetectorID]struct{}, len(detectors))diff --git a/pkg/engine/verifier_auth_test.go b/pkg/engine/verifier_auth_test.gonew file mode 100644index 000000000..dd8d62b60--- /dev/null+++ b/pkg/engine/verifier_auth_test.go@@ -0,0 +1,107 @@+package engine++import (+ "net/http"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/trufflesecurity/trufflehog/v3/pkg/config"+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors"+ "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth"+ "github.com/trufflesecurity/trufflehog/v3/pkg/engine/defaults"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"+ "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb"+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources"+)++func testVerifierAuth(t *testing.T) *verifierauth.Config {+ t.Helper()+ cfg, err := verifierauth.FromProto(&custom_detectorspb.VerifierAuth{+ AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{Oauth2: &custom_detectorspb.OAuth2Config{+ TokenEndpoint: "https://idp.example.com/token",+ TokenHeader: "X-Auth-Proxy-Token",+ GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{Ropc: &custom_detectorspb.ROPCConfig{+ Username: "svc", Password: "pw", ClientId: "client",+ }},+ }},+ }, false)+ require.NoError(t, err)+ return cfg+}++func verifierAuthEngineConfig(endpoints map[string]string, auth map[config.DetectorID]*verifierauth.Config) Config {+ return Config{+ Concurrency: 1,+ Detectors: defaults.DefaultDetectors(),+ Verify: false,+ SourceManager: sources.NewManager(),+ Dispatcher: NewPrinterDispatcher(new(discardPrinter)),+ VerifierEndpoints: endpoints,+ VerifierAuth: auth,+ }+}++func TestNewEngine_AttachesVerifierAuthToCustomVerifierDetectors(t *testing.T) {+ gitlab := config.DetectorID{ID: detector_typepb.DetectorType_Gitlab}+ conf := verifierAuthEngineConfig(+ map[string]string{"gitlab": "https://authproxy.example.com/gitlab"},+ map[config.DetectorID]*verifierauth.Config{gitlab: testVerifierAuth(t)},+ )++ e, err := NewEngine(context.Background(), &conf)+ require.NoError(t, err)++ type authAware interface {+ Endpoints(...string) []string+ VerificationClient(*http.Client) *http.Client+ }+ var checked int+ base := &http.Client{}+ for _, det := range e.detectors {+ d, ok := det.(authAware)+ if !ok {+ continue+ }+ if det.Type() == detector_typepb.DetectorType_Gitlab {+ // Every GitLab version shares the unversioned auth entry: only the+ // configured endpoint is used, and verification goes through the+ // auth transport.+ assert.Equal(t, []string{"https://authproxy.example.com/gitlab"}, d.Endpoints("https://found.example.com"))+ assert.NotSame(t, base, d.VerificationClient(base))+ checked+++ continue+ }+ assert.Same(t, base, d.VerificationClient(base), "detector %s must not receive auth", det.Type())+ }+ assert.Positive(t, checked, "no GitLab detector found")+}++func TestNewEngine_RejectsVerifierAuthWithoutEndpoints(t *testing.T) {+ gitlab := config.DetectorID{ID: detector_typepb.DetectorType_Gitlab}+ conf := verifierAuthEngineConfig(+ map[string]string{"github": "https://authproxy.example.com/github"},+ map[config.DetectorID]*verifierauth.Config{gitlab: testVerifierAuth(t)},+ )++ _, err := NewEngine(context.Background(), &conf)+ assert.ErrorContains(t, err, "without custom verifier endpoints")+}++func TestValidateVerifierAuth_RejectsDetectorWithoutAuthSupport(t *testing.T) {+ aws := config.DetectorID{ID: detector_typepb.DetectorType_AWS}+ require.NotContains(t, defaults.DefaultDetectorTypesImplementing[detectors.VerifierAuthCustomizer](), aws.ID)++ err := validateVerifierAuth(+ map[config.DetectorID]*verifierauth.Config{aws: testVerifierAuth(t)},+ map[config.DetectorID][]string{aws: {"https://authproxy.example.com"}},+ )+ assert.ErrorContains(t, err, "does not support verifier auth")+}++func TestValidateVerifierAuth_IgnoresNilEntries(t *testing.T) {+ gitlab := config.DetectorID{ID: detector_typepb.DetectorType_Gitlab}+ assert.NoError(t, validateVerifierAuth(map[config.DetectorID]*verifierauth.Config{gitlab: nil}, nil))+}diff --git a/pkg/pb/custom_detectorspb/custom_detectors.pb.go b/pkg/pb/custom_detectorspb/custom_detectors.pb.goindex 7341903a8..8a8ae137e 100644--- a/pkg/pb/custom_detectorspb/custom_detectors.pb.go+++ b/pkg/pb/custom_detectorspb/custom_detectors.pb.go@@ -205,6 +205,9 @@ type VerifierConfig struct {Headers []string `protobuf:"bytes,3,rep,name=headers,proto3" json:"headers,omitempty"`SuccessRanges []string `protobuf:"bytes,4,rep,name=successRanges,proto3" json:"successRanges,omitempty"`RotatedRanges []string `protobuf:"bytes,5,rep,name=rotatedRanges,proto3" json:"rotatedRanges,omitempty"`+ // Optional authentication for verification requests, for endpoints that+ // sit behind an auth proxy.+ Auth *VerifierAuth `protobuf:"bytes,6,opt,name=auth,proto3" json:"auth,omitempty"`}func (x *VerifierConfig) Reset() {@@ -274,6 +277,256 @@ func (x *VerifierConfig) GetRotatedRanges() []string {return nil}+func (x *VerifierConfig) GetAuth() *VerifierAuth {+ if x != nil {+ return x.Auth+ }+ return nil+}++// VerifierAuth selects how verification requests authenticate to the auth+// proxy in front of the verification endpoint. Exactly one mechanism may be+// set.+type VerifierAuth struct {+ state protoimpl.MessageState+ sizeCache protoimpl.SizeCache+ unknownFields protoimpl.UnknownFields++ // Types that are assignable to AuthConfig:+ //+ // *VerifierAuth_Oauth2+ AuthConfig isVerifierAuth_AuthConfig `protobuf_oneof:"auth_config"`+}++func (x *VerifierAuth) Reset() {+ *x = VerifierAuth{}+ if protoimpl.UnsafeEnabled {+ mi := &file_custom_detectors_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+ }+}++func (x *VerifierAuth) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*VerifierAuth) ProtoMessage() {}++func (x *VerifierAuth) ProtoReflect() protoreflect.Message {+ mi := &file_custom_detectors_proto_msgTypes[3]+ if protoimpl.UnsafeEnabled && x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use VerifierAuth.ProtoReflect.Descriptor instead.+func (*VerifierAuth) Descriptor() ([]byte, []int) {+ return file_custom_detectors_proto_rawDescGZIP(), []int{3}+}++func (m *VerifierAuth) GetAuthConfig() isVerifierAuth_AuthConfig {+ if m != nil {+ return m.AuthConfig+ }+ return nil+}++func (x *VerifierAuth) GetOauth2() *OAuth2Config {+ if x, ok := x.GetAuthConfig().(*VerifierAuth_Oauth2); ok {+ return x.Oauth2+ }+ return nil+}++type isVerifierAuth_AuthConfig interface {+ isVerifierAuth_AuthConfig()+}++type VerifierAuth_Oauth2 struct {+ Oauth2 *OAuth2Config `protobuf:"bytes,1,opt,name=oauth2,proto3,oneof"`+}++func (*VerifierAuth_Oauth2) isVerifierAuth_AuthConfig() {}++// OAuth2Config obtains an access token from an OAuth2 identity provider and+// attaches it to every verification request sent to a configured endpoint.+type OAuth2Config struct {+ state protoimpl.MessageState+ sizeCache protoimpl.SizeCache+ unknownFields protoimpl.UnknownFields++ // Token endpoint of the identity provider. Must be HTTPS unless the+ // verifier is marked unsafe.+ TokenEndpoint string `protobuf:"bytes,1,opt,name=token_endpoint,json=tokenEndpoint,proto3" json:"token_endpoint,omitempty"`+ // Types that are assignable to GrantConfig:+ //+ // *OAuth2Config_Ropc+ GrantConfig isOAuth2Config_GrantConfig `protobuf_oneof:"grant_config"`+ // Request header that carries the access token as "Bearer <token>".+ // Defaults to "Authorization". Detectors that send the secret under test+ // in Authorization need a different header here, because the token is+ // never allowed to overwrite a header the detector set.+ TokenHeader string `protobuf:"bytes,3,opt,name=token_header,json=tokenHeader,proto3" json:"token_header,omitempty"`+}++func (x *OAuth2Config) Reset() {+ *x = OAuth2Config{}+ if protoimpl.UnsafeEnabled {+ mi := &file_custom_detectors_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+ }+}++func (x *OAuth2Config) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*OAuth2Config) ProtoMessage() {}++func (x *OAuth2Config) ProtoReflect() protoreflect.Message {+ mi := &file_custom_detectors_proto_msgTypes[4]+ if protoimpl.UnsafeEnabled && x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use OAuth2Config.ProtoReflect.Descriptor instead.+func (*OAuth2Config) Descriptor() ([]byte, []int) {+ return file_custom_detectors_proto_rawDescGZIP(), []int{4}+}++func (x *OAuth2Config) GetTokenEndpoint() string {+ if x != nil {+ return x.TokenEndpoint+ }+ return ""+}++func (m *OAuth2Config) GetGrantConfig() isOAuth2Config_GrantConfig {+ if m != nil {+ return m.GrantConfig+ }+ return nil+}++func (x *OAuth2Config) GetRopc() *ROPCConfig {+ if x, ok := x.GetGrantConfig().(*OAuth2Config_Ropc); ok {+ return x.Ropc+ }+ return nil+}++func (x *OAuth2Config) GetTokenHeader() string {+ if x != nil {+ return x.TokenHeader+ }+ return ""+}++type isOAuth2Config_GrantConfig interface {+ isOAuth2Config_GrantConfig()+}++type OAuth2Config_Ropc struct {+ Ropc *ROPCConfig `protobuf:"bytes,2,opt,name=ropc,proto3,oneof"`+}++func (*OAuth2Config_Ropc) isOAuth2Config_GrantConfig() {}++// ROPCConfig holds credentials for the OAuth2 Resource Owner Password+// Credentials grant (RFC 6749 section 4.3).+type ROPCConfig struct {+ state protoimpl.MessageState+ sizeCache protoimpl.SizeCache+ unknownFields protoimpl.UnknownFields++ Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`+ Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`+ ClientId string `protobuf:"bytes,3,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`+ ClientSecret string `protobuf:"bytes,4,opt,name=client_secret,json=clientSecret,proto3" json:"client_secret,omitempty"`+ // Space-separated scopes to request. Empty requests no scope.+ Scope string `protobuf:"bytes,5,opt,name=scope,proto3" json:"scope,omitempty"`+}++func (x *ROPCConfig) Reset() {+ *x = ROPCConfig{}+ if protoimpl.UnsafeEnabled {+ mi := &file_custom_detectors_proto_msgTypes[5]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+ }+}++func (x *ROPCConfig) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ROPCConfig) ProtoMessage() {}++func (x *ROPCConfig) ProtoReflect() protoreflect.Message {+ mi := &file_custom_detectors_proto_msgTypes[5]+ if protoimpl.UnsafeEnabled && x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ROPCConfig.ProtoReflect.Descriptor instead.+func (*ROPCConfig) Descriptor() ([]byte, []int) {+ return file_custom_detectors_proto_rawDescGZIP(), []int{5}+}++func (x *ROPCConfig) GetUsername() string {+ if x != nil {+ return x.Username+ }+ return ""+}++func (x *ROPCConfig) GetPassword() string {+ if x != nil {+ return x.Password+ }+ return ""+}++func (x *ROPCConfig) GetClientId() string {+ if x != nil {+ return x.ClientId+ }+ return ""+}++func (x *ROPCConfig) GetClientSecret() string {+ if x != nil {+ return x.ClientSecret+ }+ return ""+}++func (x *ROPCConfig) GetScope() string {+ if x != nil {+ return x.Scope+ }+ return ""+}+type ValidationConfig struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCache@@ -288,7 +541,7 @@ type ValidationConfig struct {func (x *ValidationConfig) Reset() {*x = ValidationConfig{}if protoimpl.UnsafeEnabled {- mi := &file_custom_detectors_proto_msgTypes[3]+ mi := &file_custom_detectors_proto_msgTypes[6]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -301,7 +554,7 @@ func (x *ValidationConfig) String() string {func (*ValidationConfig) ProtoMessage() {}func (x *ValidationConfig) ProtoReflect() protoreflect.Message {- mi := &file_custom_detectors_proto_msgTypes[3]+ mi := &file_custom_detectors_proto_msgTypes[6]if protoimpl.UnsafeEnabled && x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -314,7 +567,7 @@ func (x *ValidationConfig) ProtoReflect() protoreflect.Message {// Deprecated: Use ValidationConfig.ProtoReflect.Descriptor instead.func (*ValidationConfig) Descriptor() ([]byte, []int) {- return file_custom_detectors_proto_rawDescGZIP(), []int{3}+ return file_custom_detectors_proto_rawDescGZIP(), []int{6}}func (x *ValidationConfig) GetContainsDigit() bool {@@ -399,7 +652,7 @@ var file_custom_detectors_proto_rawDesc = []byte{0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x63, 0x75, 0x73, 0x74,0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x2e, 0x56, 0x61, 0x6c,0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x05, 0x76,- 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xb4, 0x01, 0x0a, 0x0e, 0x56, 0x65, 0x72,+ 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xe8, 0x01, 0x0a, 0x0e, 0x56, 0x65, 0x72,0x69, 0x66, 0x69, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x24, 0x0a, 0x08, 0x65,0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x08, 0xfa,0x42, 0x05, 0x72, 0x03, 0x90, 0x01, 0x01, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e,@@ -410,25 +663,54 @@ var file_custom_detectors_proto_rawDesc = []byte{0x6e, 0x67, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0d, 0x73, 0x75, 0x63, 0x63,0x65, 0x73, 0x73, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x12, 0x24, 0x0a, 0x0d, 0x72, 0x6f, 0x74,0x61, 0x74, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09,- 0x52, 0x0d, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x22,- 0xcb, 0x01, 0x0a, 0x10, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f,- 0x6e, 0x66, 0x69, 0x67, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73,- 0x5f, 0x64, 0x69, 0x67, 0x69, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x63, 0x6f,- 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x44, 0x69, 0x67, 0x69, 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x63,- 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x5f, 0x6c, 0x6f, 0x77, 0x65, 0x72, 0x63, 0x61, 0x73,- 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,- 0x73, 0x4c, 0x6f, 0x77, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x6f,- 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x5f, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65,- 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73,- 0x55, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x15, 0x63, 0x6f, 0x6e,- 0x74, 0x61, 0x69, 0x6e, 0x73, 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x61, 0x6c, 0x5f, 0x63, 0x68,- 0x61, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69,- 0x6e, 0x73, 0x53, 0x70, 0x65, 0x63, 0x69, 0x61, 0x6c, 0x43, 0x68, 0x61, 0x72, 0x42, 0x44, 0x5a,- 0x42, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x72, 0x75, 0x66,- 0x66, 0x6c, 0x65, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2f, 0x74, 0x72, 0x75, 0x66,- 0x66, 0x6c, 0x65, 0x68, 0x6f, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x62,- 0x2f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72,- 0x73, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,+ 0x52, 0x0d, 0x72, 0x6f, 0x74, 0x61, 0x74, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x12,+ 0x32, 0x0a, 0x04, 0x61, 0x75, 0x74, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e,+ 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73,+ 0x2e, 0x56, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x72, 0x41, 0x75, 0x74, 0x68, 0x52, 0x04, 0x61,+ 0x75, 0x74, 0x68, 0x22, 0x57, 0x0a, 0x0c, 0x56, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x72, 0x41,+ 0x75, 0x74, 0x68, 0x12, 0x38, 0x0a, 0x06, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x32, 0x18, 0x01, 0x20,+ 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74,+ 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x2e, 0x4f, 0x41, 0x75, 0x74, 0x68, 0x32, 0x43, 0x6f, 0x6e,+ 0x66, 0x69, 0x67, 0x48, 0x00, 0x52, 0x06, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x32, 0x42, 0x0d, 0x0a,+ 0x0b, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x9c, 0x01, 0x0a,+ 0x0c, 0x4f, 0x41, 0x75, 0x74, 0x68, 0x32, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x25, 0x0a,+ 0x0e, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18,+ 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x45, 0x6e, 0x64, 0x70,+ 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x32, 0x0a, 0x04, 0x72, 0x6f, 0x70, 0x63, 0x18, 0x02, 0x20, 0x01,+ 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74, 0x65,+ 0x63, 0x74, 0x6f, 0x72, 0x73, 0x2e, 0x52, 0x4f, 0x50, 0x43, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,+ 0x48, 0x00, 0x52, 0x04, 0x72, 0x6f, 0x70, 0x63, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x6f, 0x6b, 0x65,+ 0x6e, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b,+ 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x42, 0x0e, 0x0a, 0x0c, 0x67,+ 0x72, 0x61, 0x6e, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x9c, 0x01, 0x0a, 0x0a,+ 0x52, 0x4f, 0x50, 0x43, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73,+ 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73,+ 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f,+ 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f,+ 0x72, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18,+ 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12,+ 0x23, 0x0a, 0x0d, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74,+ 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x65,+ 0x63, 0x72, 0x65, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x05, 0x20,+ 0x01, 0x28, 0x09, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x22, 0xcb, 0x01, 0x0a, 0x10, 0x56,+ 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12,+ 0x25, 0x0a, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x5f, 0x64, 0x69, 0x67, 0x69,+ 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,+ 0x73, 0x44, 0x69, 0x67, 0x69, 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69,+ 0x6e, 0x73, 0x5f, 0x6c, 0x6f, 0x77, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01,+ 0x28, 0x08, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x4c, 0x6f, 0x77, 0x65,+ 0x72, 0x63, 0x61, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,+ 0x73, 0x5f, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28,+ 0x08, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x55, 0x70, 0x70, 0x65, 0x72,+ 0x63, 0x61, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x15, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73,+ 0x5f, 0x73, 0x70, 0x65, 0x63, 0x69, 0x61, 0x6c, 0x5f, 0x63, 0x68, 0x61, 0x72, 0x18, 0x04, 0x20,+ 0x01, 0x28, 0x08, 0x52, 0x13, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x53, 0x70, 0x65,+ 0x63, 0x69, 0x61, 0x6c, 0x43, 0x68, 0x61, 0x72, 0x42, 0x44, 0x5a, 0x42, 0x67, 0x69, 0x74, 0x68,+ 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x73, 0x65,+ 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2f, 0x74, 0x72, 0x75, 0x66, 0x66, 0x6c, 0x65, 0x68, 0x6f,+ 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x62, 0x2f, 0x63, 0x75, 0x73, 0x74,+ 0x6f, 0x6d, 0x5f, 0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x70, 0x62, 0x62, 0x06,+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,}var (@@ -443,26 +725,32 @@ func file_custom_detectors_proto_rawDescGZIP() []byte {return file_custom_detectors_proto_rawDescData}-var file_custom_detectors_proto_msgTypes = make([]protoimpl.MessageInfo, 6)+var file_custom_detectors_proto_msgTypes = make([]protoimpl.MessageInfo, 9)var file_custom_detectors_proto_goTypes = []interface{}{(*CustomDetectors)(nil), // 0: custom_detectors.CustomDetectors(*CustomRegex)(nil), // 1: custom_detectors.CustomRegex(*VerifierConfig)(nil), // 2: custom_detectors.VerifierConfig- (*ValidationConfig)(nil), // 3: custom_detectors.ValidationConfig- nil, // 4: custom_detectors.CustomRegex.RegexEntry- nil, // 5: custom_detectors.CustomRegex.ValidationsEntry+ (*VerifierAuth)(nil), // 3: custom_detectors.VerifierAuth+ (*OAuth2Config)(nil), // 4: custom_detectors.OAuth2Config+ (*ROPCConfig)(nil), // 5: custom_detectors.ROPCConfig+ (*ValidationConfig)(nil), // 6: custom_detectors.ValidationConfig+ nil, // 7: custom_detectors.CustomRegex.RegexEntry+ nil, // 8: custom_detectors.CustomRegex.ValidationsEntry}var file_custom_detectors_proto_depIdxs = []int32{1, // 0: custom_detectors.CustomDetectors.detectors:type_name -> custom_detectors.CustomRegex- 4, // 1: custom_detectors.CustomRegex.regex:type_name -> custom_detectors.CustomRegex.RegexEntry+ 7, // 1: custom_detectors.CustomRegex.regex:type_name -> custom_detectors.CustomRegex.RegexEntry2, // 2: custom_detectors.CustomRegex.verify:type_name -> custom_detectors.VerifierConfig- 5, // 3: custom_detectors.CustomRegex.validations:type_name -> custom_detectors.CustomRegex.ValidationsEntry- 3, // 4: custom_detectors.CustomRegex.ValidationsEntry.value:type_name -> custom_detectors.ValidationConfig- 5, // [5:5] is the sub-list for method output_type- 5, // [5:5] is the sub-list for method input_type- 5, // [5:5] is the sub-list for extension type_name- 5, // [5:5] is the sub-list for extension extendee- 0, // [0:5] is the sub-list for field type_name+ 8, // 3: custom_detectors.CustomRegex.validations:type_name -> custom_detectors.CustomRegex.ValidationsEntry+ 3, // 4: custom_detectors.VerifierConfig.auth:type_name -> custom_detectors.VerifierAuth+ 4, // 5: custom_detectors.VerifierAuth.oauth2:type_name -> custom_detectors.OAuth2Config+ 5, // 6: custom_detectors.OAuth2Config.ropc:type_name -> custom_detectors.ROPCConfig+ 6, // 7: custom_detectors.CustomRegex.ValidationsEntry.value:type_name -> custom_detectors.ValidationConfig+ 8, // [8:8] is the sub-list for method output_type+ 8, // [8:8] is the sub-list for method input_type+ 8, // [8:8] is the sub-list for extension type_name+ 8, // [8:8] is the sub-list for extension extendee+ 0, // [0:8] is the sub-list for field type_name}func init() { file_custom_detectors_proto_init() }@@ -508,6 +796,42 @@ func file_custom_detectors_proto_init() {}}file_custom_detectors_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {+ switch v := v.(*VerifierAuth); i {+ case 0:+ return &v.state+ case 1:+ return &v.sizeCache+ case 2:+ return &v.unknownFields+ default:+ return nil+ }+ }+ file_custom_detectors_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {+ switch v := v.(*OAuth2Config); i {+ case 0:+ return &v.state+ case 1:+ return &v.sizeCache+ case 2:+ return &v.unknownFields+ default:+ return nil+ }+ }+ file_custom_detectors_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {+ switch v := v.(*ROPCConfig); i {+ case 0:+ return &v.state+ case 1:+ return &v.sizeCache+ case 2:+ return &v.unknownFields+ default:+ return nil+ }+ }+ file_custom_detectors_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {switch v := v.(*ValidationConfig); i {case 0:return &v.state@@ -520,13 +844,19 @@ func file_custom_detectors_proto_init() {}}}+ file_custom_detectors_proto_msgTypes[3].OneofWrappers = []interface{}{+ (*VerifierAuth_Oauth2)(nil),+ }+ file_custom_detectors_proto_msgTypes[4].OneofWrappers = []interface{}{+ (*OAuth2Config_Ropc)(nil),+ }type x struct{}out := protoimpl.TypeBuilder{File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: file_custom_detectors_proto_rawDesc,NumEnums: 0,- NumMessages: 6,+ NumMessages: 9,NumExtensions: 0,NumServices: 0,},diff --git a/pkg/pb/custom_detectorspb/custom_detectors.pb.validate.go b/pkg/pb/custom_detectorspb/custom_detectors.pb.validate.goindex 9e0a31eb4..1a537b0f9 100644--- a/pkg/pb/custom_detectorspb/custom_detectors.pb.validate.go+++ b/pkg/pb/custom_detectorspb/custom_detectors.pb.validate.go@@ -394,6 +394,35 @@ func (m *VerifierConfig) validate(all bool) error {// no validation rules for Unsafe+ if all {+ switch v := interface{}(m.GetAuth()).(type) {+ case interface{ ValidateAll() error }:+ if err := v.ValidateAll(); err != nil {+ errors = append(errors, VerifierConfigValidationError{+ field: "Auth",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ case interface{ Validate() error }:+ if err := v.Validate(); err != nil {+ errors = append(errors, VerifierConfigValidationError{+ field: "Auth",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ }+ } else if v, ok := interface{}(m.GetAuth()).(interface{ Validate() error }); ok {+ if err := v.Validate(); err != nil {+ return VerifierConfigValidationError{+ field: "Auth",+ reason: "embedded message failed validation",+ cause: err,+ }+ }+ }+if len(errors) > 0 {return VerifierConfigMultiError(errors)}@@ -472,6 +501,409 @@ var _ interface {ErrorName() string} = VerifierConfigValidationError{}+// Validate checks the field values on VerifierAuth with the rules defined in+// the proto definition for this message. If any rules are violated, the first+// error encountered is returned, or nil if there are no violations.+func (m *VerifierAuth) Validate() error {+ return m.validate(false)+}++// ValidateAll checks the field values on VerifierAuth with the rules defined+// in the proto definition for this message. If any rules are violated, the+// result is a list of violation errors wrapped in VerifierAuthMultiError, or+// nil if none found.+func (m *VerifierAuth) ValidateAll() error {+ return m.validate(true)+}++func (m *VerifierAuth) validate(all bool) error {+ if m == nil {+ return nil+ }++ var errors []error++ switch v := m.AuthConfig.(type) {+ case *VerifierAuth_Oauth2:+ if v == nil {+ err := VerifierAuthValidationError{+ field: "AuthConfig",+ reason: "oneof value cannot be a typed-nil",+ }+ if !all {+ return err+ }+ errors = append(errors, err)+ }++ if all {+ switch v := interface{}(m.GetOauth2()).(type) {+ case interface{ ValidateAll() error }:+ if err := v.ValidateAll(); err != nil {+ errors = append(errors, VerifierAuthValidationError{+ field: "Oauth2",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ case interface{ Validate() error }:+ if err := v.Validate(); err != nil {+ errors = append(errors, VerifierAuthValidationError{+ field: "Oauth2",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ }+ } else if v, ok := interface{}(m.GetOauth2()).(interface{ Validate() error }); ok {+ if err := v.Validate(); err != nil {+ return VerifierAuthValidationError{+ field: "Oauth2",+ reason: "embedded message failed validation",+ cause: err,+ }+ }+ }++ default:+ _ = v // ensures v is used+ }++ if len(errors) > 0 {+ return VerifierAuthMultiError(errors)+ }++ return nil+}++// VerifierAuthMultiError is an error wrapping multiple validation errors+// returned by VerifierAuth.ValidateAll() if the designated constraints aren't met.+type VerifierAuthMultiError []error++// Error returns a concatenation of all the error messages it wraps.+func (m VerifierAuthMultiError) Error() string {+ var msgs []string+ for _, err := range m {+ msgs = append(msgs, err.Error())+ }+ return strings.Join(msgs, "; ")+}++// AllErrors returns a list of validation violation errors.+func (m VerifierAuthMultiError) AllErrors() []error { return m }++// VerifierAuthValidationError is the validation error returned by+// VerifierAuth.Validate if the designated constraints aren't met.+type VerifierAuthValidationError struct {+ field string+ reason string+ cause error+ key bool+}++// Field function returns field value.+func (e VerifierAuthValidationError) Field() string { return e.field }++// Reason function returns reason value.+func (e VerifierAuthValidationError) Reason() string { return e.reason }++// Cause function returns cause value.+func (e VerifierAuthValidationError) Cause() error { return e.cause }++// Key function returns key value.+func (e VerifierAuthValidationError) Key() bool { return e.key }++// ErrorName returns error name.+func (e VerifierAuthValidationError) ErrorName() string { return "VerifierAuthValidationError" }++// Error satisfies the builtin error interface+func (e VerifierAuthValidationError) Error() string {+ cause := ""+ if e.cause != nil {+ cause = fmt.Sprintf(" | caused by: %v", e.cause)+ }++ key := ""+ if e.key {+ key = "key for "+ }++ return fmt.Sprintf(+ "invalid %sVerifierAuth.%s: %s%s",+ key,+ e.field,+ e.reason,+ cause)+}++var _ error = VerifierAuthValidationError{}++var _ interface {+ Field() string+ Reason() string+ Key() bool+ Cause() error+ ErrorName() string+} = VerifierAuthValidationError{}++// Validate checks the field values on OAuth2Config with the rules defined in+// the proto definition for this message. If any rules are violated, the first+// error encountered is returned, or nil if there are no violations.+func (m *OAuth2Config) Validate() error {+ return m.validate(false)+}++// ValidateAll checks the field values on OAuth2Config with the rules defined+// in the proto definition for this message. If any rules are violated, the+// result is a list of violation errors wrapped in OAuth2ConfigMultiError, or+// nil if none found.+func (m *OAuth2Config) ValidateAll() error {+ return m.validate(true)+}++func (m *OAuth2Config) validate(all bool) error {+ if m == nil {+ return nil+ }++ var errors []error++ // no validation rules for TokenEndpoint++ // no validation rules for TokenHeader++ switch v := m.GrantConfig.(type) {+ case *OAuth2Config_Ropc:+ if v == nil {+ err := OAuth2ConfigValidationError{+ field: "GrantConfig",+ reason: "oneof value cannot be a typed-nil",+ }+ if !all {+ return err+ }+ errors = append(errors, err)+ }++ if all {+ switch v := interface{}(m.GetRopc()).(type) {+ case interface{ ValidateAll() error }:+ if err := v.ValidateAll(); err != nil {+ errors = append(errors, OAuth2ConfigValidationError{+ field: "Ropc",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ case interface{ Validate() error }:+ if err := v.Validate(); err != nil {+ errors = append(errors, OAuth2ConfigValidationError{+ field: "Ropc",+ reason: "embedded message failed validation",+ cause: err,+ })+ }+ }+ } else if v, ok := interface{}(m.GetRopc()).(interface{ Validate() error }); ok {+ if err := v.Validate(); err != nil {+ return OAuth2ConfigValidationError{+ field: "Ropc",+ reason: "embedded message failed validation",+ cause: err,+ }+ }+ }++ default:+ _ = v // ensures v is used+ }++ if len(errors) > 0 {+ return OAuth2ConfigMultiError(errors)+ }++ return nil+}++// OAuth2ConfigMultiError is an error wrapping multiple validation errors+// returned by OAuth2Config.ValidateAll() if the designated constraints aren't met.+type OAuth2ConfigMultiError []error++// Error returns a concatenation of all the error messages it wraps.+func (m OAuth2ConfigMultiError) Error() string {+ var msgs []string+ for _, err := range m {+ msgs = append(msgs, err.Error())+ }+ return strings.Join(msgs, "; ")+}++// AllErrors returns a list of validation violation errors.+func (m OAuth2ConfigMultiError) AllErrors() []error { return m }++// OAuth2ConfigValidationError is the validation error returned by+// OAuth2Config.Validate if the designated constraints aren't met.+type OAuth2ConfigValidationError struct {+ field string+ reason string+ cause error+ key bool+}++// Field function returns field value.+func (e OAuth2ConfigValidationError) Field() string { return e.field }++// Reason function returns reason value.+func (e OAuth2ConfigValidationError) Reason() string { return e.reason }++// Cause function returns cause value.+func (e OAuth2ConfigValidationError) Cause() error { return e.cause }++// Key function returns key value.+func (e OAuth2ConfigValidationError) Key() bool { return e.key }++// ErrorName returns error name.+func (e OAuth2ConfigValidationError) ErrorName() string { return "OAuth2ConfigValidationError" }++// Error satisfies the builtin error interface+func (e OAuth2ConfigValidationError) Error() string {+ cause := ""+ if e.cause != nil {+ cause = fmt.Sprintf(" | caused by: %v", e.cause)+ }++ key := ""+ if e.key {+ key = "key for "+ }++ return fmt.Sprintf(+ "invalid %sOAuth2Config.%s: %s%s",+ key,+ e.field,+ e.reason,+ cause)+}++var _ error = OAuth2ConfigValidationError{}++var _ interface {+ Field() string+ Reason() string+ Key() bool+ Cause() error+ ErrorName() string+} = OAuth2ConfigValidationError{}++// Validate checks the field values on ROPCConfig with the rules defined in the+// proto definition for this message. If any rules are violated, the first+// error encountered is returned, or nil if there are no violations.+func (m *ROPCConfig) Validate() error {+ return m.validate(false)+}++// ValidateAll checks the field values on ROPCConfig with the rules defined in+// the proto definition for this message. If any rules are violated, the+// result is a list of violation errors wrapped in ROPCConfigMultiError, or+// nil if none found.+func (m *ROPCConfig) ValidateAll() error {+ return m.validate(true)+}++func (m *ROPCConfig) validate(all bool) error {+ if m == nil {+ return nil+ }++ var errors []error++ // no validation rules for Username++ // no validation rules for Password++ // no validation rules for ClientId++ // no validation rules for ClientSecret++ // no validation rules for Scope++ if len(errors) > 0 {+ return ROPCConfigMultiError(errors)+ }++ return nil+}++// ROPCConfigMultiError is an error wrapping multiple validation errors+// returned by ROPCConfig.ValidateAll() if the designated constraints aren't met.+type ROPCConfigMultiError []error++// Error returns a concatenation of all the error messages it wraps.+func (m ROPCConfigMultiError) Error() string {+ var msgs []string+ for _, err := range m {+ msgs = append(msgs, err.Error())+ }+ return strings.Join(msgs, "; ")+}++// AllErrors returns a list of validation violation errors.+func (m ROPCConfigMultiError) AllErrors() []error { return m }++// ROPCConfigValidationError is the validation error returned by+// ROPCConfig.Validate if the designated constraints aren't met.+type ROPCConfigValidationError struct {+ field string+ reason string+ cause error+ key bool+}++// Field function returns field value.+func (e ROPCConfigValidationError) Field() string { return e.field }++// Reason function returns reason value.+func (e ROPCConfigValidationError) Reason() string { return e.reason }++// Cause function returns cause value.+func (e ROPCConfigValidationError) Cause() error { return e.cause }++// Key function returns key value.+func (e ROPCConfigValidationError) Key() bool { return e.key }++// ErrorName returns error name.+func (e ROPCConfigValidationError) ErrorName() string { return "ROPCConfigValidationError" }++// Error satisfies the builtin error interface+func (e ROPCConfigValidationError) Error() string {+ cause := ""+ if e.cause != nil {+ cause = fmt.Sprintf(" | caused by: %v", e.cause)+ }++ key := ""+ if e.key {+ key = "key for "+ }++ return fmt.Sprintf(+ "invalid %sROPCConfig.%s: %s%s",+ key,+ e.field,+ e.reason,+ cause)+}++var _ error = ROPCConfigValidationError{}++var _ interface {+ Field() string+ Reason() string+ Key() bool+ Cause() error+ ErrorName() string+} = ROPCConfigValidationError{}+// Validate checks the field values on ValidationConfig with the rules defined// in the proto definition for this message. If any rules are violated, the// first error encountered is returned, or nil if there are no violations.diff --git a/proto/custom_detectors.proto b/proto/custom_detectors.protoindex ebc0ea548..bae94d664 100644--- a/proto/custom_detectors.proto+++ b/proto/custom_detectors.proto@@ -31,6 +31,45 @@ message VerifierConfig {repeated string headers = 3;repeated string successRanges = 4;repeated string rotatedRanges = 5;+ // Optional authentication for verification requests, for endpoints that+ // sit behind an auth proxy.+ VerifierAuth auth = 6;+}++// VerifierAuth selects how verification requests authenticate to the auth+// proxy in front of the verification endpoint. Exactly one mechanism may be+// set.+message VerifierAuth {+ oneof auth_config {+ OAuth2Config oauth2 = 1;+ }+}++// OAuth2Config obtains an access token from an OAuth2 identity provider and+// attaches it to every verification request sent to a configured endpoint.+message OAuth2Config {+ // Token endpoint of the identity provider. Must be HTTPS unless the+ // verifier is marked unsafe.+ string token_endpoint = 1;+ oneof grant_config {+ ROPCConfig ropc = 2;+ }+ // Request header that carries the access token as "Bearer <token>".+ // Defaults to "Authorization". Detectors that send the secret under test+ // in Authorization need a different header here, because the token is+ // never allowed to overwrite a header the detector set.+ string token_header = 3;+}++// ROPCConfig holds credentials for the OAuth2 Resource Owner Password+// Credentials grant (RFC 6749 section 4.3).+message ROPCConfig {+ string username = 1;+ string password = 2;+ string client_id = 3;+ string client_secret = 4;+ // Space-separated scopes to request. Empty requests no scope.+ string scope = 5;}message ValidationConfig {