Skip to content
Changes

Reference

verifierauth · Oct 7, 2026

What this change means

Atlas added verifierauth to its detector catalog in this update.

pkg/detectors/verifierauth/token_source.go+166−0View file
@@ -0,0 +1,166 @@
1added: package verifierauth
2added:
3added: import (
4added: "context"
5added: "fmt"
6added: "net/http"
7added: "strings"
8added: "sync"
9added: "time"
10added:
11added: "github.com/go-logr/logr"
12added: "golang.org/x/oauth2"
13added:
14added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"
15added: )
16added:
17added: // defaultTokenLifetime is applied when the identity provider omits
18added: // expires_in from its token response. RFC 6749 makes expires_in optional,
19added: // and oauth2 leaves Expiry zero in that case, which ReuseTokenSource treats
20added: // as "never expires". Without a default, one token would be reused for the
21added: // life of the process and every verification would fail once the IdP
22added: // expired it.
23added: const defaultTokenLifetime = 5 * time.Minute
24added:
25added: // ropcTokenSource performs the OAuth2 Resource Owner Password Credentials
26added: // exchange (RFC 6749 section 4.3). It only fetches; caching and refresh are
27added: // layered on top by ReuseTokenSource, and failure backoff by
28added: // tokenErrorCache.
29added: type ropcTokenSource struct {
30added: conf *oauth2.Config
31added: username string
32added: password string
33added: // client performs the token request. It is deliberately separate from
34added: // the detector's client: the token endpoint is the identity provider
35added: // that issues tokens for the auth proxy, not a verification endpoint, so
36added: // detector-specific transport rules (such as blocking private IPs) do
37added: // not apply to it.
38added: client *http.Client
39added: now func() time.Time
40added: logger func() logr.Logger
41added: }
42added:
43added: // newROPCTokenSource builds an unwrapped ROPC token source. Client
44added: // credentials are sent in the request body (AuthStyleInParams) rather than
45added: // as HTTP basic auth, which is what password-grant deployments of the
46added: // identity providers we target expect.
47added: func newROPCTokenSource(
48added: tokenEndpoint string,
49added: ropc *custom_detectorspb.ROPCConfig,
50added: client *http.Client,
51added: now func() time.Time,
52added: logger func() logr.Logger,
53added: ) *ropcTokenSource {
54added: return &ropcTokenSource{
55added: conf: &oauth2.Config{
56added: ClientID: ropc.GetClientId(),
57added: ClientSecret: ropc.GetClientSecret(),
58added: Endpoint: oauth2.Endpoint{
59added: TokenURL: tokenEndpoint,
60added: AuthStyle: oauth2.AuthStyleInParams,
61added: },
62added: Scopes: strings.Fields(ropc.GetScope()),
63added: },
64added: username: ropc.GetUsername(),
65added: password: ropc.GetPassword(),
66added: client: client,
67added: now: now,
68added: logger: logger,
69added: }
70added: }
71added:
72added: // Token fetches a new access token.
73added: //
74added: // oauth2.TokenSource.Token takes no context, so the request context is
75added: // rooted in Background and the HTTP client travels on it under the
76added: // oauth2.HTTPClient key, which is how the oauth2 package selects a client.
77added: // The client's timeout is what bounds a hung identity provider.
78added: func (s *ropcTokenSource) Token() (*oauth2.Token, error) {
79added: ctx := context.WithValue(context.Background(), oauth2.HTTPClient, s.client)
80added:
81added: s.logger().V(2).Info("requesting verifier access token")
82added: tok, err := s.conf.PasswordCredentialsToken(ctx, s.username, s.password)
83added: if err != nil {
84added: return nil, fmt.Errorf("ropc token request failed: %w", err)
85added: }
86added:
87added: if tok.Expiry.IsZero() {
88added: tok.Expiry = s.now().Add(defaultTokenLifetime)
89added: s.logger().V(1).Info("identity provider did not return expires_in; using default token lifetime",
90added: "default_lifetime", defaultTokenLifetime,
91added: )
92added: }
93added: s.logger().V(1).Info("obtained verifier access token", "expires_at", tok.Expiry)
94added: return tok, nil
95added: }
96added:
97added: // Backoff bounds for tokenErrorCache. The window starts small so a brief
98added: // IdP blip clears quickly, and is capped so that wrong credentials cost at
99added: // most one failed login per maxTokenErrorBackoff, which keeps the scanner
100added: // from tripping the identity provider's account lockout policy.
101added: const (
102added: minTokenErrorBackoff = 5 * time.Second
103added: maxTokenErrorBackoff = 5 * time.Minute
104added: )
105added:
106added: // tokenErrorCache remembers the most recent token fetch failure and answers
107added: // with it, without contacting the IdP, until a backoff window passes.
108added: // ReuseTokenSource already caches successful tokens; this is the
109added: // counterpart for failures.
110added: //
111added: // It never sleeps. Callers inside a window get the cached error
112added: // immediately, so a failing or hung IdP turns verification for the affected
113added: // auth config into fast "unable to verify" results instead of tying up the
114added: // shared detector worker pool behind token request timeouts. The window
115added: // doubles on each consecutive failure up to maxTokenErrorBackoff and resets
116added: // on the first success.
117added: type tokenErrorCache struct {
118added: base oauth2.TokenSource
119added: now func() time.Time
120added: onFailure func(err error, retryIn time.Duration)
121added:
122added: mu sync.Mutex
123added: lastErr error
124added: retryAt time.Time
125added: window time.Duration
126added: }
127added:
128added: func newTokenErrorCache(base oauth2.TokenSource, now func() time.Time, onFailure func(error, time.Duration)) *tokenErrorCache {
129added: return &tokenErrorCache{base: base, now: now, onFailure: onFailure}
130added: }
131added:
132added: // Token returns a fresh token from the base source, or the cached failure
133added: // while a backoff window is open.
134added: //
135added: // The mutex is held across the base fetch so that, when a window expires,
136added: // exactly one caller makes the next attempt and the rest observe its
137added: // outcome. ReuseTokenSource provides the same serialization in production;
138added: // holding the lock here keeps this type correct on its own.
139added: func (c *tokenErrorCache) Token() (*oauth2.Token, error) {
140added: c.mu.Lock()
141added: defer c.mu.Unlock()
142added:
143added: if c.lastErr != nil && c.now().Before(c.retryAt) {
144added: return nil, fmt.Errorf("token fetch failed recently; next attempt after %s: %w",
145added: c.retryAt.Format(time.RFC3339), c.lastErr)
146added: }
147added:
148added: tok, err := c.base.Token()
149added: if err != nil {
150added: if c.window == 0 {
151added: c.window = minTokenErrorBackoff
152added: } else {
153added: c.window = min(2*c.window, maxTokenErrorBackoff)
154added: }
155added: c.lastErr = err
156added: c.retryAt = c.now().Add(c.window)
157added: if c.onFailure != nil {
158added: c.onFailure(err, c.window)
159added: }
160added: return nil, err
161added: }
162added:
163added: c.lastErr = nil
164added: c.window = 0
165added: return tok, nil
166added: }
pkg/detectors/verifierauth/transport.go+164−0View file
@@ -0,0 +1,164 @@
1added: package verifierauth
2added:
3added: import (
4added: "errors"
5added: "fmt"
6added: "net"
7added: "net/http"
8added: "net/url"
9added: "strings"
10added: )
11added:
12added: // The errors below reach detectors wrapped in *url.Error by http.Client, and
13added: // both are deliberately leaf errors with no Unwrap. Two consumers depend on
14added: // that:
15added: // - Result.SetVerificationError keeps only the innermost error's message,
16added: // so the leaf is what users see as the verification error. It has to
17added: // say "verifier auth" and carry the oauth2_trace for log correlation.
18added: // - Detectors classify request errors to decide that the verification
19added: // host does not exist, by substring ("no such host", "dial tcp") or by
20added: // errors.As into *net.DNSError. An IdP failure must not be mistaken for
21added: // a missing verification host, so the IdP's error is neither in the
22added: // message nor reachable through the chain.
23added:
24added: // ErrHeaderCollision reports that a request already carries the header the
25added: // access token would be written to. Built-in detectors commonly send the
26added: // secret under test in Authorization; overwriting it would hand the
27added: // verification service the token instead of the secret and produce wrong
28added: // verdicts, so the request is refused instead. The fix is to set tokenHeader
29added: // to a header the auth proxy reads. Match it with errors.Is.
30added: var ErrHeaderCollision = errors.New("verifier auth token header is already set by the detector; set oauth2 tokenHeader to a different header")
31added:
32added: // headerCollisionError is the ErrHeaderCollision instance returned for a
33added: // request, adding the header name and trace to the message.
34added: type headerCollisionError struct {
35added: header string
36added: trace string
37added: }
38added:
39added: func (e *headerCollisionError) Error() string {
40added: return fmt.Sprintf("%v (header %q, oauth2_trace=%s)", ErrHeaderCollision, e.header, e.trace)
41added: }
42added:
43added: func (e *headerCollisionError) Is(target error) bool { return target == ErrHeaderCollision }
44added:
45added: // TokenError reports that no access token could be obtained, so the request
46added: // was not sent. The IdP's error is kept in Err for callers that ask for it
47added: // with errors.As, and every real fetch failure is logged with the same
48added: // oauth2_trace and the token endpoint.
49added: type TokenError struct {
50added: Trace string
51added: Err error
52added: }
53added:
54added: func (e *TokenError) Error() string {
55added: return fmt.Sprintf("verifier auth: could not obtain access token (oauth2_trace=%s; see logs for the cause)", e.Trace)
56added: }
57added:
58added: // WrapClient returns a copy of base whose transport attaches an access token
59added: // to requests bound for allowedEndpoints. Timeout, redirect policy, and
60added: // cookie jar are carried over from base unchanged; base itself is not
61added: // modified.
62added: //
63added: // Only the scheme and host of each allowed endpoint are matched, because
64added: // detectors append their own API paths to the configured endpoint.
65added: // Requests to any other host pass through without a token. The check runs
66added: // on every round trip, so a redirect to another host never carries the
67added: // token either.
68added: func (c *Config) WrapClient(base *http.Client, allowedEndpoints []string) *http.Client {
69added: clone := *base
70added: rt := base.Transport
71added: if rt == nil {
72added: rt = http.DefaultTransport
73added: }
74added: clone.Transport = &authTransport{
75added: base: rt,
76added: cfg: c,
77added: allowed: originsOf(allowedEndpoints),
78added: }
79added: return &clone
80added: }
81added:
82added: // originsOf reduces endpoints to their lowercase scheme://host form.
83added: // Endpoints that don't parse as absolute URLs contribute nothing, which
84added: // means no token is ever sent on their behalf.
85added: func originsOf(endpoints []string) map[string]struct{} {
86added: origins := make(map[string]struct{}, len(endpoints))
87added: for _, endpoint := range endpoints {
88added: u, err := url.Parse(endpoint)
89added: if err != nil || u.Scheme == "" || u.Host == "" {
90added: continue
91added: }
92added: origins[origin(u)] = struct{}{}
93added: }
94added: return origins
95added: }
96added:
97added: // defaultPorts maps each scheme a verifier endpoint may use to the port it
98added: // implies when the URL names none.
99added: var defaultPorts = map[string]string{"http": "80", "https": "443"}
100added:
101added: // origin reduces u to the lowercase scheme://host[:port] key used for the
102added: // allowlist. url.URL keeps the host exactly as written, so the same server
103added: // can arrive as "https://h" or "https://h:443": the configured endpoint and
104added: // a detector's rebuilt request URL need not agree on spelling. The default
105added: // port for the scheme is dropped so both forms produce one key; dropping it
106added: // (rather than always adding it) matches how endpoints are usually written.
107added: // Non-default ports are kept, so "https://h:8443" stays a different origin.
108added: func origin(u *url.URL) string {
109added: scheme := strings.ToLower(u.Scheme)
110added: host := strings.ToLower(u.Hostname())
111added: if port := u.Port(); port != "" && port != defaultPorts[scheme] {
112added: host = net.JoinHostPort(host, port)
113added: } else if strings.Contains(host, ":") {
114added: // Hostname strips the brackets from an IPv6 literal, and
115added: // JoinHostPort only restores them when there is a port.
116added: host = "[" + host + "]"
117added: }
118added: return scheme + "://" + host
119added: }
120added:
121added: // authTransport attaches the access token to requests for allowed origins.
122added: type authTransport struct {
123added: base http.RoundTripper
124added: cfg *Config
125added: allowed map[string]struct{}
126added: }
127added:
128added: // RoundTrip attaches the token and forwards the request, or fails it
129added: // without sending anything. Every failure is returned as a request error,
130added: // which detectors already report as a verification error, never as "not
131added: // verified".
132added: //
133added: // The token is set on a clone because a RoundTripper must not modify the
134added: // caller's request. That also keeps the token off the request http.Client
135added: // reuses to build redirects; each redirect hop comes back through here and
136added: // is checked against the allowlist again.
137added: func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
138added: if _, ok := t.allowed[origin(req.URL)]; !ok {
139added: return t.base.RoundTrip(req)
140added: }
141added:
142added: if len(req.Header.Values(t.cfg.tokenHeader)) > 0 {
143added: closeBody(req)
144added: return nil, &headerCollisionError{header: t.cfg.tokenHeader, trace: t.cfg.trace}
145added: }
146added:
147added: tok, err := t.cfg.tokens.Token()
148added: if err != nil {
149added: closeBody(req)
150added: return nil, &TokenError{Trace: t.cfg.trace, Err: err}
151added: }
152added:
153added: authed := req.Clone(req.Context())
154added: authed.Header.Set(t.cfg.tokenHeader, "Bearer "+tok.AccessToken)
155added: return t.base.RoundTrip(authed)
156added: }
157added:
158added: // closeBody honors the RoundTripper contract that the request body is
159added: // closed even when RoundTrip returns an error without sending.
160added: func closeBody(req *http.Request) {
161added: if req.Body != nil {
162added: _ = req.Body.Close()
163added: }
164added: }
pkg/detectors/verifierauth/verifierauth.go+148−0View file
@@ -0,0 +1,148 @@
1added: // Package verifierauth authenticates verification requests to endpoints that
2added: // sit behind an auth proxy: an OAuth-protected component in front of a
3added: // verification service that requires an access token before it forwards a
4added: // request to that service.
5added: //
6added: // Authentication is purely an HTTP-client concern. A Config wraps a
7added: // detector's existing *http.Client so every request to a configured endpoint
8added: // carries an access token, while the detector keeps full ownership of its
9added: // request shape and of how responses map to verdicts. The wrapper never
10added: // decides "verified" or "not verified"; it either attaches a token or fails
11added: // the request, and a failed request surfaces as a verification error
12added: // ("unable to verify").
13added: //
14added: // The package sits below pkg/detectors so that both pkg/detectors
15added: // (EndpointSetter, used by built-in detectors) and pkg/custom_detectors can
16added: // use it. It must never import either of them.
17added: package verifierauth
18added:
19added: import (
20added: "errors"
21added: "fmt"
22added: "net/http"
23added: "strings"
24added: "time"
25added:
26added: "github.com/go-logr/logr"
27added: "github.com/google/uuid"
28added: "golang.org/x/net/http/httpguts"
29added: "golang.org/x/oauth2"
30added:
31added: "github.com/trufflesecurity/trufflehog/v3/pkg/common"
32added: logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"
33added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"
34added: )
35added:
36added: // DefaultTokenHeader is the header that carries the access token when the
37added: // configuration does not name one.
38added: const DefaultTokenHeader = "Authorization"
39added:
40added: // Config is a validated, ready-to-use verifier authentication setup. One
41added: // Config is shared by every request (and every detector worker) that uses
42added: // the same auth block, so its token cache and token error cache are shared
43added: // too. A nil *Config means "no auth configured".
44added: type Config struct {
45added: tokens oauth2.TokenSource
46added: tokenHeader string
47added: tokenEndpoint string
48added: // trace correlates every log line and error produced for this auth
49added: // config, so an operator can follow one auth block from token fetch
50added: // through to the verification requests that used it.
51added: trace string
52added: }
53added:
54added: // FromProto validates an auth block and builds a Config from it. It returns
55added: // (nil, nil) when auth is nil, so callers can pass the field through
56added: // unconditionally.
57added: //
58added: // No token is fetched here. Token acquisition is deferred to the first
59added: // verification request that needs one, so an unreachable identity provider
60added: // degrades verification for the affected detector instead of failing
61added: // startup, and the rest of the scan proceeds. Only the structure of the
62added: // config is checked up front.
63added: //
64added: // unsafe has the same meaning as on VerifierConfig: it permits a plain
65added: // http:// token endpoint.
66added: func FromProto(auth *custom_detectorspb.VerifierAuth, unsafe bool) (*Config, error) {
67added: if auth == nil {
68added: return nil, nil
69added: }
70added: oc := auth.GetOauth2()
71added: if oc == nil {
72added: return nil, errors.New("auth is set but names no auth mechanism (expected oauth2)")
73added: }
74added: if err := ValidateEndpoint(oc.GetTokenEndpoint(), unsafe); err != nil {
75added: return nil, fmt.Errorf("oauth2 tokenEndpoint: %w", err)
76added: }
77added:
78added: tokenHeader := oc.GetTokenHeader()
79added: if tokenHeader == "" {
80added: tokenHeader = DefaultTokenHeader
81added: }
82added: if !httpguts.ValidHeaderFieldName(tokenHeader) {
83added: return nil, fmt.Errorf("oauth2 tokenHeader %q is not a valid HTTP header name", tokenHeader)
84added: }
85added:
86added: ropc := oc.GetRopc()
87added: if ropc == nil {
88added: return nil, errors.New("oauth2 auth names no grant (expected ropc)")
89added: }
90added: switch {
91added: case ropc.GetUsername() == "":
92added: return nil, errors.New("oauth2 ropc username is required")
93added: case ropc.GetPassword() == "":
94added: return nil, errors.New("oauth2 ropc password is required")
95added: case ropc.GetClientId() == "":
96added: return nil, errors.New("oauth2 ropc clientId is required")
97added: }
98added:
99added: cfg := &Config{
100added: tokenHeader: http.CanonicalHeaderKey(tokenHeader),
101added: tokenEndpoint: oc.GetTokenEndpoint(),
102added: trace: uuid.NewString(),
103added: }
104added: base := newROPCTokenSource(oc.GetTokenEndpoint(), ropc, common.SaneHttpClient(), time.Now, cfg.logger)
105added: errCache := newTokenErrorCache(base, time.Now, func(err error, retryIn time.Duration) {
106added: cfg.logger().Error(err, "failed to obtain verifier access token; verification for this auth config is unavailable until the retry",
107added: "retry_in", retryIn,
108added: )
109added: })
110added: // ReuseTokenSource caches the token and refreshes it shortly before it
111added: // expires. It serializes callers on its own lock while a fetch is in
112added: // flight, so concurrent detector workers trigger at most one fetch.
113added: cfg.tokens = oauth2.ReuseTokenSource(nil, errCache)
114added: return cfg, nil
115added: }
116added:
117added: // TokenHeader reports the canonical header name that carries the token.
118added: // Callers that build requests from user-supplied headers use it to reject a
119added: // configuration that would collide with the token at load time.
120added: func (c *Config) TokenHeader() string {
121added: return c.tokenHeader
122added: }
123added:
124added: // logger returns a logger tagged with this config's trace ID. It resolves
125added: // the default logger at call time rather than at construction, so log
126added: // output follows whatever logger the process configured after startup.
127added: func (c *Config) logger() logr.Logger {
128added: return logContext.Background().Logger().WithValues(
129added: "oauth2_trace", c.trace,
130added: "token_endpoint", c.tokenEndpoint,
131added: )
132added: }
133added:
134added: // ValidateEndpoint enforces the transport rule shared by verification
135added: // endpoints and token endpoints: the endpoint must be set, and plain http://
136added: // is only allowed when the verifier is explicitly marked unsafe. It lives
137added: // here, rather than in pkg/custom_detectors, so this package can apply the
138added: // same rule to token endpoints without importing custom_detectors.
139added: func ValidateEndpoint(endpoint string, unsafe bool) error {
140added: if len(endpoint) == 0 {
141added: return fmt.Errorf("no endpoint")
142added: }
143added:
144added: if strings.HasPrefix(endpoint, "http://") && !unsafe {
145added: return fmt.Errorf("http endpoint must have unsafe=true")
146added: }
147added: return nil
148added: }
pkg/detectors/verifierauth/verifierauthtest/verifierauthtest.go+83−0View file
@@ -0,0 +1,83 @@
1added: // Package verifierauthtest supports tests outside verifierauth that exercise
2added: // the verifier auth path: a fake OAuth2 identity provider that issues a fixed
3added: // access token, and a helper that builds a verifierauth.Config against it.
4added: // It is imported only from tests, so it never ends up in the binary.
5added: package verifierauthtest
6added:
7added: import (
8added: "encoding/json"
9added: "net/http"
10added: "net/http/httptest"
11added: "sync/atomic"
12added: "testing"
13added:
14added: "github.com/trufflesecurity/trufflehog/v3/pkg/detectors/verifierauth"
15added: "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb"
16added: )
17added:
18added: // AccessToken is the access token the fake IdP issues. Verification servers
19added: // in tests expect it as "Bearer " + AccessToken in the configured header.
20added: const AccessToken = "auth-proxy-access-token"
21added:
22added: // IdP is a fake OAuth2 token endpoint for the ROPC grant. It answers every
23added: // token request with AccessToken until RejectCredentials is called.
24added: type IdP struct {
25added: *httptest.Server
26added: hits atomic.Int32
27added: rejected atomic.Bool
28added: }
29added:
30added: // NewIdP starts a fake IdP that is closed when the test ends.
31added: func NewIdP(t testing.TB) *IdP {
32added: t.Helper()
33added: idp := &IdP{}
34added: idp.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
35added: idp.hits.Add(1)
36added: w.Header().Set("Content-Type", "application/json")
37added: if idp.rejected.Load() {
38added: w.WriteHeader(http.StatusUnauthorized)
39added: _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant"})
40added: return
41added: }
42added: _ = json.NewEncoder(w).Encode(map[string]any{
43added: "access_token": AccessToken,
44added: "token_type": "Bearer",
45added: "expires_in": 3600,
46added: })
47added: }))
48added: t.Cleanup(idp.Close)
49added: return idp
50added: }
51added:
52added: // RejectCredentials makes every later token request fail with invalid_grant,
53added: // which is how an IdP answers wrong service account credentials.
54added: func (idp *IdP) RejectCredentials() { idp.rejected.Store(true) }
55added:
56added: // Hits reports how many token requests the IdP has received.
57added: func (idp *IdP) Hits() int { return int(idp.hits.Load()) }
58added:
59added: // Config builds a verifier auth config that fetches tokens from idp and
60added: // writes them to tokenHeader (empty means the default, Authorization). The
61added: // fake IdP is plain HTTP, so the config is built with unsafe set.
62added: func Config(t testing.TB, idp *IdP, tokenHeader string) *verifierauth.Config {
63added: t.Helper()
64added: cfg, err := verifierauth.FromProto(&custom_detectorspb.VerifierAuth{
65added: AuthConfig: &custom_detectorspb.VerifierAuth_Oauth2{
66added: Oauth2: &custom_detectorspb.OAuth2Config{
67added: TokenEndpoint: idp.URL,
68added: TokenHeader: tokenHeader,
69added: GrantConfig: &custom_detectorspb.OAuth2Config_Ropc{
70added: Ropc: &custom_detectorspb.ROPCConfig{
71added: Username: "svc-scanner",
72added: Password: "svc-password",
73added: ClientId: "scanner-client",
74added: },
75added: },
76added: },
77added: },
78added: }, true)
79added: if err != nil {
80added: t.Fatalf("building verifier auth config: %v", err)
81added: }
82added: return cfg
83added: }